How can I downcast a dyn trait into another trait in Rust?

Viewed 537

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:

  1. 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`
  1. I tried the same static thing using as or an intermediate variable.

  2. I tried dynamically casting using Any and downcast_ref, but I couldn't get the magic right.

0 Answers
Related