Skip to main content
Be Bitwise
RustTraits & Generics

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.

rust
fn notify<T: Summary>(item: &T) {
println!("{}", item.summarize());
}
// Compiler creates notify::<Article> and notify::<Tweet> separately

Dynamic dispatch (trait objects): the correct method is looked up at runtime.

rust
fn notify(item: &dyn Summary) {
println!("{}", item.summarize());
}
// One function, dispatches at runtime via vtable

Trait Objects with dyn

rust
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.

Key Concept

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 self by reference (&self, &mut self) or through a pointer such as Box<Self>, don't return Self, 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.

rust
// 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:

rust
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

CriterionGenericsTrait Objects
PerformanceFaster (inlined)Slight overhead (vtable)
Binary sizeLarger (monomorphized)Smaller
Heterogeneous collectionsNot possiblePossible
Compile-time typeKnownUnknown

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.

Try itPredict the three sizes (the fat pointer is the giveaway), then uncomment the last line to see why Clone can't go behind dyn.
Rust (1.40.0)

Challenges

Implement a Summary trait with a summarize() method for a NewsArticle struct.

Rust (1.40.0)