I have some confusion about Deref coercion. I read that Deref coercion is used implicitly when there is a type mismatch.
consider following code:
fn main() {
let x = X;
let r = &x;
r.show(); // prints referenced
}
trait Tr {
fn show(&self);
}
struct X;
impl Tr for &X {
fn show(&self) {
println!("referenced");
}
}
the above code prints referenced
.
now add new trait implementation on owned type:
fn main() {
let x = X;
let r = &x;
r.show(); // prints owned
}
trait Tr {
fn show(&self);
}
struct X;
impl Tr for &X {
fn show(&self) {
println!("referenced");
}
}
impl Tr for X {
fn show(&self) {
println!("owned");
}
}
now it prints owned
but I am expecting it to print referenced
.
since &X
implements trait Tr
, there is no type mismatch. so it should not be derefed implicitly.
is there some thing wrong in my understanding. I also found no way to get it printing referenced
after adding new Tr
implementation other than using generics with trait bounds.