I read this answer but I'm still confused.
How do you interpret
impl B for dyn A {}
?trait A { fn method_a(&self) { println!("a"); } } trait B { fn method_b(&self) { println!("b") } } impl B for dyn A {} impl A for i32 {} fn main() { let x: &dyn A = &10; x.method_b(); }
I can understand
impl A for i32 {}
becausei32
is a concrete type.dyn A
is not a concrete type (unsized, can't pass by value), and you cannot declare adyn A
but you can only declare a&dyn A
. Should I interpret// x.method_b(); (*x).method_b();
as
*x
isdyn A
?I can also declare
impl B for &dyn A {}
, so why I needimpl B for dyn A {}
? What's the use case?Follow up: If I modify the code
fn main() { let x: &dyn A = &10; // have a B trait object over dyn A since // dyn A implements B let y: &dyn B = x; }
It will fail and complain
&dyn A
is not&dyn B
. I understand this is a reasonable complain but I provide the option for compiler to useimpl B for dyn A {}
. Apparently, the compiler doesn't consider that's an option.