Maik Klein
Maik Klein

Reputation: 16148

How does Rust manage to have generics without overloaded functions?

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
}

Upvotes: 5

Views: 292

Answers (1)

Vladimir Matveev
Vladimir Matveev

Reputation: 127761

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.

Upvotes: 4

Related Questions