Calling impl Trait func with a Box<dyn Trait>

I have a function that takes an impl Trait argument, but I have a Box

trait Foo{}

fn main() {
    //
    let a: Box<dyn Foo> = ....
}

fn bar(val: impl Foo){
    //
}

Can I somehow call bar() here with a?
I know downcasting exists but would that work here?

If you own Foo, you can do

trait Foo {
    fn m(&self) -> &str;
}

struct S0;
impl Foo for S0 {
    fn m(&self) -> &str {"S0's m"}
}

impl Foo for Box<dyn Foo> {
    fn m(&self) -> &str {(**self).m()}
}

fn main() {
    let a: Box<dyn Foo> = Box::new(S0);
    bar(a);
}

fn bar(val: impl Foo) {
    println!("{}", val.m());
}

You can add an impl Foo for Box<dyn Foo> and then use the box directly.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.