Trait Objects & Dynamic Dispatch
Trait objects let you handle a mix of types through one shared trait at runtime. Polymorphism, Rust-style.
Static vs Dynamic Dispatch
Static dispatch (generics): the compiler generates code for each concrete type.
fn notify<T: Summary>(item: &T) { println!("{}", item.summarize());}// Compiler creates notify::<Article> and notify::<Tweet> separatelyDynamic dispatch (trait objects): the correct method is looked up at runtime.
fn notify(item: &dyn Summary) { println!("{}", item.summarize());}// One function, dispatches at runtime via vtableTrait Objects with dyn
let shapes: Vec<Box<dyn Shape>> = vec![ Box::new(Circle { radius: 5.0 }), Box::new(Rectangle { width: 3.0, height: 4.0 }),];
for shape in &shapes { println!("Area: {:.2}", shape.area());}Box<dyn Shape> is a trait object — a fat pointer carrying both the data pointer and a vtable pointer.
Follow shape.area() for the rectangle. The loop variable is the fat pointer, two words wide. The call loads the vtable pointer, loads the area slot from the vtable, and makes an indirect call with the data pointer as self. rustc's vtables also carry the drop function, size and alignment ahead of the methods, which is how Box knows how to free a value whose type it no longer knows:
With generics there's no middle box. A fn total<T: Shape>(s: &[T]) call for Rectangle jumps straight to Rectangle::area, or has it inlined. Module 7 lesson 3 shows both in assembly.
Reach for generics (static dispatch) when every type is known at compile time. The dispatch is direct, often inlined, and skips the vtable hop. Trait objects earn their place when you need a mixed bag of types in one collection, or when you only learn the concrete type at runtime.
Dyn Compatibility
Not every trait can sit behind dyn. The Rust Reference calls the property dyn compatibility; older docs and compiler versions call it object safety. Roughly, a trait qualifies if:
- It doesn't require
Self: Sized. - Its methods take
selfby reference (&self,&mut self) or through a pointer such asBox<Self>, don't returnSelf, and have no generic type parameters.
A method that breaks the method rules can stay if you mark it where Self: Sized. It just isn't callable through a trait object.
// Dyn compatible:trait Draw { fn draw(&self);}
// NOT dyn compatible: Clone requires Sized (and clone returns Self)trait Clone: Sized { fn clone(&self) -> Self;}The Strategy Pattern
Trait objects enable the strategy pattern:
trait Formatter { fn format(&self, data: &str) -> String;}
struct JsonFormatter;impl Formatter for JsonFormatter { fn format(&self, data: &str) -> String { format!("{{\"data\": \"{}\"}}", data) }}
struct PlainFormatter;impl Formatter for PlainFormatter { fn format(&self, data: &str) -> String { data.to_string() }}
fn process(data: &str, formatter: &dyn Formatter) { println!("{}", formatter.format(data));}When to Choose Each
| Criterion | Generics | Trait Objects |
|---|---|---|
| Performance | Faster (inlined) | Slight overhead (vtable) |
| Binary size | Larger (monomorphized) | Smaller |
| Heterogeneous collections | Not possible | Possible |
| Compile-time type | Known | Unknown |
In practice, start with generics. Reach for trait objects when you need runtime polymorphism, or when monomorphisation starts puffing up your binary.
Here's the formatter as a pipeline of trait objects, next to a generic call. Guess how big each pointer is before you run it.
Challenges
Implement a Summary trait with a summarize() method for a NewsArticle struct.