The following code, where a struct implements two traits that both require a method with the same name (fun
):
trait OnlySelf {
fn fun(&self);
}
trait SelfAndInt {
fn fun(&self, a: usize);
}
struct S;
impl OnlySelf for S {
fn fun(&self) {
println!("Hello");
}
}
impl SelfAndInt for S {
fn fun(&self, a: usize) {
println!("Hello, {}", a);
}
}
fn main() {
let a = S;
a.fun();
a.fun(1);
}
fails to compile with the following error:
error[E0034]: multiple applicable items in scope
--> src/main.rs:24:7
|
24 | a.fun();
| ^^^ multiple `fun` found
The argument count of each trait's method is different however, therefore there is only one valid way in which a.fun()
and a.fun(1)
can be interpreted, namely a.fun() ≡ OnlySelf::fun(&a)
and a.fun(1) ≡ SelfAndInt::fun(&a, 1)
.
Is the compiler protecting me from some sort of footgun or it isn't (yet?) smart enough to infer which method has to be used each time? Maybe inferring this can become too expensive so it is purposefully left out of rustc
?