I\'m trying to create a trait and provide one implementation for all non-reference types, and another for all reference types.
This fails to compile:
The reason for the Clone
version works is because the types that the trait is being implemented for are no longer conflicting on the implementation.
Take the first example and add a default implementation.
trait Foo {
fn hi(&self){
println!("Hi");
}
}
And then we implement Foo
for all of type T
with impl
this actually implements enough for us to use a reference to our types and use the Foo
trait. For Example:
fn say_hi<'a>(b: &'a mut Foo){
b.hi();
}
fn main(){
let mut five = 5;
five.hi(); // integer using Foo
say_hi(&mut five); // &'a mut Foo
}
To answer the second part of you question, you didn't need the second implement of impl<'a,T> Foo for &'a mut T {}
because impl
was enough to give you what you were looking for.
Now that we have seen that the first example works without the second implement it starts to make sense that the example using Clone
works because you are implementing for a subset of types T
that are Clone
and a different subset of types &'a mut T
that are Clone+static