What's the difference between &dyn Trait and Box<dyn Trait> for dynamic dispatch?

Viewed 3135

Functions new_foo1 and new_foo2 return the same trait Foo using different patterns. I don't see any functional difference between them besides new_foo1 being more verbose. Is there a preferred way among the two? Is there any subtle ramifications of either pattern?

trait Foo {
    fn bar(&self);
}

struct FooIm {}

impl Foo for FooIm {
    fn bar(&self) {
        println!("bar from FooIm")
    }
}

fn new_foo1<'a>() -> &'a (dyn Foo + 'a) {
    &FooIm {}
}

fn new_foo2() -> Box<dyn Foo> {
    let f = FooIm {};
    Box::new(f)
}

fn main() {
    let f1 = new_foo1();
    let f2 = new_foo2();

    f1.bar();
    f2.bar();
}
0 Answers
Related