Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Rust manage to have generics without overloaded functions?

Tags:

rust

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
}
like image 290
Maik Klein Avatar asked Sep 30 '22 00:09

Maik Klein


1 Answers

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.

like image 142
Vladimir Matveev Avatar answered Oct 17 '22 08:10

Vladimir Matveev