Rust Fundamentals interview question · Most asked

What's the difference between impl Trait, generics and dyn Trait?

Create a free account to save this page, take notes and track your progress. Sign in

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

More most-asked Rust Fundamentals questions

← All Rust Fundamentals questions

Was this page helpful?