Trait objects
A trait object is dyn Trait: a value whose concrete type is erased and whose methods are called through a vtable. You almost always store it behind a pointer, such as Box<dyn Trait>.
Detailed Explanation
A generic T: Draw is compiled once per concrete T. A Box<dyn Draw> is one type at runtime that can hold a Button today and a Label tomorrow. The box stores two pointers: one to the value, one to a vtable of Draw methods for that value's type. Calling widget.draw() loads the function pointer from the vtable and jumps. That is dynamic dispatch.
dyn Trait is unsized. You cannot write let w: dyn Draw = button and you cannot put dyn Draw in a struct field by value. You put it behind a pointer that carries the missing length-or-vtable information: Box<dyn Draw>, &dyn Draw, Arc<dyn Draw>. The pointer is a fat pointer, two words wide.
Not every trait can become a trait object. The trait must be object-safe. No method may return Self by value, take Self by value (except the receiver), or have generic type parameters. Those methods need a concrete Self the vtable cannot provide. Clone::clone returns Self, so dyn Clone does not exist. Iterator is object-safe; clone on an iterator is not available through dyn Iterator unless you add a helper trait.
You write dyn Trait explicitly. Older Rust allowed Box<Trait> as a shorthand; that form is gone. You may add lifetime and auto-trait bounds: Box<dyn Draw + Send + Sync> is a widget you can move to another thread. + 'static is common for values stored in global caches.
Why this exists: a windowing system has a list of widgets of different types. Monomorphising a Vec<T> cannot hold mixed T. A trait object can. The cost is the vtable call, the extra allocation if you use Box, and the loss of any method that was not on the trait. You also lose specialisation: the compiler cannot inline Button::draw through dyn Draw unless it devirtualises, which it rarely can.
When you reach for a trait object: mixed types, or a public API that must not leak a generic parameter. When every call site has one concrete type, a generic bound is faster and richer.
Code Examples
trait Draw {
fn draw(&self);
}
struct Button;
struct Label;
impl Draw for Button {
fn draw(&self) {
println!("button");
}
}
impl Draw for Label {
fn draw(&self) {
println!("label");
}
}
fn main() {
let widgets: Vec<Box<dyn Draw>> = vec![Box::new(Button), Box::new(Label)];
for w in &widgets {
w.draw();
}
// prints:
// button
// label
}Common Gotchas
Not every trait is object-safe
A method that returns `Self` or is generic makes `dyn Trait` illegal. Split those methods onto a second trait, or keep the API generic.
`dyn Trait` is unsized
Store it as `Box<dyn Trait>` or `&dyn Trait`. A field of type `dyn Trait` by value will not compile.
Fat pointers are two words
`size_of::<&dyn Draw>()` is twice `size_of::<&Button>()`. Passing many trait objects by value of the reference is still cheap; cloning `Box<dyn _>` allocates.
Write `dyn` explicitly
`Box<Draw>` is no longer valid. The keyword makes the dynamic dispatch visible in the type.