Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 25: Traits, Rust’s Core Abstraction

You will understand

  • Traits as named capabilities, not interfaces
  • Static dispatch via monomorphization
  • When to use impl Trait vs dyn Trait

Reading time

35 min
+ 20 min exercises
Capability Map

Traits as Named Capabilities

Vec <i32> Debug Clone IntoIterator Default
Monomorphization

One Generic Function, Many Concrete Instantiations

fn largest<T: PartialOrd>(...) largest_i32 largest_f64 largest_Point static dispatch specialize for the types actually used

Here is dynamic dispatch with nothing hidden: the fat pointer, the vtable, and the indirect jump.

Interactive simulation (requires JavaScript): Box<dyn Speak> is a fat pointer — a data pointer to the heap value plus a vtable pointer into static memory; calling speak() looks up the function in the vtable and jumps, costing one indirection versus the inlined static dispatch of generics.

## Step 1 - The Problem