On this page
  1. Traits, Generics & Dispatch
  2. Contents
  3. Static Dispatch (Monomorphization)
  4. Dynamic Dispatch (dyn Trait Fat Pointers)
  5. Associated Types & The Orphan Rule

Traits, Generics & Dispatch

Prev: Ownership, Borrowing, Lifetimes & RAII | Up: ownership_and_internals | Next: Enums, Pattern Matching & Error Propagation
Rel: Polymorphism & Dispatch, C Vtables
Ref: The Rust Book — Traits
Tags: #public #prog #rust #internals #traits


Contents


Static Dispatch (Monomorphization)

Generic bounds (fn draw<T: Shape>(s: &T) or fn draw(s: &impl Shape)) generate specialized machine code per concrete type at compile time — zero vtable indirection and full inlining:

trait Area {
    fn area(&self) -> f64;
}

fn print_area(shape: &impl Area) {
    println!("area = {:.2}", shape.area());
}

Dynamic Dispatch (dyn Trait Fat Pointers)

When storing heterogeneous types in one collection (Vec<Box<dyn Area>>), Rust creates a two-word fat pointer (data_ptr, vtable_ptr) for runtime dispatch.


Associated Types & The Orphan Rule

Linked from

Related notes