In the book Rust for Rustaceans, the author writes:
Broadly speaking, though, you’ll want to use static dispatch in your libraries and dynamic dispatch in your binaries. In a library, you want to allow your users to decide what kind of dispatch is best for them, since you don’t know what their needs are.
I guess that, in the binary case, he refers to this:
fn flexible_dispatch_method(_: &dyn MyTrait) {}
// static dispatch
//
let obj = MyType {};
flexible_dispatch_method(&obj);
// dynamic dispatch
//
let trait_obj: &dyn MyTrait = &MyType {};
flexible_dispatch_method(trait_obj);
Given the above, what's the advantage of using boxed objects instead of trait objects? Is it because of the need to use lifetimes:
fn return_new_trait_object<'a>() -> &'a dyn MyTrait {
&MyType {}
}
or there is something else? Based on my understanding, in the dynamic dispatch case, the object needs to be allocated in the heap, anyway, so I presume there isn't much difference with a boxed object.