fn add<T: Add<T,T>>(a: T, b: T) -> T{
a + b
}
fn main() {
println!("{}", add(10i,5));
}
I know that Rust doesn't allow overloaded functions.
1.) Is add generated at compile time?
2.) If 1.) is true, how does it achieve this without overloaded functions?
In my head the compiler would generate
fn add(a: i32, b: i32) -> i32{
a + b
}
fn add(a: f32, b: f32) -> f32{
a + b
}
Usually function overloading means that you yourself can define functions with the same name but with different set of arguments. As Rust does not have overloading, it won't compile the second piece of code.
Generics, however, can be used to implement simple form of overloading - when "overloaded" functions have exactly the same implementation, but work with different types.
So, both of your points are true: add()
is generated at compile time, and yes, the snippet you provided is exactly the thing the compiler would generate (except for function names, of course); it's that overloading has nothing to do with this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With