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.
Previous
What are the thiserror and anyhow crates for error handling?
Next
What are generics in Rust and how do where clauses work?
More Rust Questions
View all →- Intermediate How does error handling with the ? operator work in Rust?
- Intermediate What are the thiserror and anyhow crates for error handling?
- Intermediate What are generics in Rust and how do where clauses work?
- Intermediate What are Rust smart pointers?
- Intermediate How does async/await work in Rust?