overview
The discussion involves:
impl Trait for Trait
Trait
(type) vsdyn Trait
(trait object type) vs&dyn Trait
(trait object)
question
I read this related answer for implement trait for trait 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
?*x
is the invalid syntax to getdyn A
, isn't it? -
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 complaint but I provide the option for compiler to useimpl B for dyn A {}
. Apparently, the compiler doesn't consider that's an option.
Originally posted in StackOverflow. I think it's better to post it here since it has more active Rustaceans here.
solution
the second part of the solution!
Thanks @daboross! Fantastic and excellent answer!!!!