According to the reference method-call-expr.html:
Then, for each candidate type
T
, search for a method with a receiver of that type in the following places:
... 2. Any of the methods provided by a trait implemented byT
If I understand this correctly, this simple code will not work: (But it works.)
trait Barkable {
fn bark(&self);
}
struct Dog{}
impl Barkable for Dog {
fn bark(&self) {
println!("woof!");
}
}
fn main() {
let d = Dog{};
d.bark();
}
Let's follow the logic:
d
is of typeDog
. Build a candidate type list: [Dog
,&Dog
, ...];- For each candidate type:
2.1.Dog
: there is no method with receiver typeDog
.
2.2.&Dog
: There is a method with receiver type&Dog
, however, it is provided by an impl onDog
, not&Dog
. This violates point 2 in the reference.
2.3. Method not found in the rest of candidate list. Thus, the method call fails.
Point 2 in the reference requires the method with receiver type T
be provided by an implementation on T
, which in this case is &Dog
. However, type &Dog
does not implement the trait.