🦀 Rust Intermediate

What are trait objects (dyn Trait) in Rust?

Answer

Trait objects (dyn Trait) enable runtime polymorphism — storing and calling values of different types through a common interface when the concrete type is not known at compile time. A trait object is a fat pointer: a pair of (data pointer, vtable pointer) where the vtable holds pointers to the concrete type's method implementations. Syntax: &dyn Drawable, Box<dyn Drawable>. Trait objects require the trait to be object-safe: no generic methods, no methods returning Self. The trade-off versus generics: trait objects allow heterogeneous collections (a Vec<Box<dyn Animal>> holding Dogs, Cats, etc.) but incur a virtual dispatch overhead and prevent inlining. Generics (static dispatch) have zero overhead but generate monomorphized code for each concrete type.