6
When should I use `Box<dyn Trait>` vs generics in Rust?
JBAsked by Jonas Berg · 16d
Both seem to let me accept many types. Trade-offs?
Both seem to let me accept many types. Trade-offs?
Accepted answer
Generics are monomorphized: fast, but bigger binaries and the type must be known at compile time. Box<dyn Trait> uses dynamic dispatch: one code path, small vtable cost, and you can store mixed types in one collection.
Sign in to answer.