Rust Fundamentals interview question · Most asked
What's the difference between impl Trait, generics and dyn Trait?
Summary
Generics and impl Trait use static dispatch: the compiler generates code per concrete type (fast, no indirection). dyn Trait is a trait object with dynamic dispatch through a vtable, allowing different types behind one pointer such as Box<dyn Trait>.
Longer Answer
Use generics by default; use trait objects for heterogeneous collections, plugin-style code or to reduce binary size and compile time.
Key Points
- Static vs dynamic dispatch.
- Box<dyn Trait> for mixed types.
- Trait bounds constrain generics.
Deep dive: Rust Fundamentals: Traits and Generics