Any time when a type may need to be heterogeneous.
In the simple case where Foo
is a struct you might do:
fn print_all(to_print: Vec<Foo>)
But if there is no such type Foo
and the method is generic with respect to multiple types you might write:
fn print_all<T>(to_print: Vec<T>)
If on the other hand Foo
is a trait, then you might write:
fn print(to_print: impl Foo)
This is generic with respect to which implementation of Foo
is passed but it can only be a single type.
If there are multiple different structs which all implement the trait Foo
you can write:
fn print_all(to_print: Vec<Box<dyn Foo>>)
This is generally not preferable to the other approaches when they can be used. However, if you need to accept/create a data structure which contains multiple different items which all implement the same trait but are not the same type, then dyn
is the only option