I have two Rust traits, and one automatically implements the other:
trait A {
fn something(&self);
}
trait B {}
impl A for dyn B {
fn something(&self) {
println!("hello from B")
}
}
Now I receive a dynamic implementation of B
, and I need to return a dynamic implementation of A
:
fn downcast(b: Box<dyn B>) -> Box<dyn A> {...}
How can I implement downcast
?
Some things I've tried:
- I tried to let Rust figure it out statically:
fn downcast(b: Box<dyn B>) -> Box<dyn A> {
b
}
This gives something like
error[E0308]: mismatched types
expected trait `A`, found trait `B`
I tried the same static thing using
as
or an intermediate variable.I tried dynamically casting using
Any
anddowncast_ref
, but I couldn't get the magic right.