Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Concepts

Static versus dynamic dispatch in Rust

Reference for Rust dispatch: generics and impl Trait (static) versus dyn Trait (dynamic), vtables, fat pointers, dyn compatibility rules, costs and when to choose each.

When code calls a trait method, the compiler must decide which implementation runs. With static dispatch the decision is made at compile time: generics and impl Trait are monomorphized, so each call goes straight to a known function and can be inlined. With dynamic dispatch the decision is made at run time: a dyn Trait value carries a pointer to a table of function pointers (a vtable), and each call looks the function up in that table.

Neither is better in general. Static dispatch is faster and lets the optimizer see through calls, but it generates code per type and requires every type to be known where the code is compiled. Dynamic dispatch allows values of different concrete types in one collection or field, and compiles once, at the cost of an indirect call and limited trait features.

Rust
fn static_call<T: Shape>(s: &T) -> f64 { s.area() }       // one copy per T
fn dynamic_call(s: &dyn Shape) -> f64 { s.area() }        // one copy, vtable call

Try it

Rust The same trait, both ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Fat pointers and upcasting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust A trait that is not dyn compatible

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

How each works

Static dispatch (generics and impl Trait)

The compiler creates a specialized copy per concrete type (monomorphization). Calls are direct, can be inlined, and the optimizer can remove them entirely. Every concrete type must be known at compile time, so a Vec<T> holds one type.

Dynamic dispatch (dyn Trait)

A &dyn Trait or Box<dyn Trait> is a fat pointer: a data pointer plus a vtable pointer. The vtable holds the destructor, the size and alignment, and one function pointer for each method. A call loads the function pointer and jumps; that blocks inlining across the call and costs a few cycles per call.

Dyn compatibility

A trait can be used as dyn Trait only if it is dyn compatible (previously called "object safe"): no method returns Self or takes Self by value (except with where Self: Sized), no generic methods, no associated constants, and Self is not required to be Sized. Add where Self: Sized to an offending method to keep the rest of the trait usable as dyn. The error for a violation is E0038.

Usage notes

  • Default to generics or impl Trait. Choose dyn when you need a heterogeneous collection, plugin-style extension, a runtime-chosen implementation, or to shrink compile time and binary size.
  • Lifetimes default to 'static in boxes: Box<dyn Trait> means Box<dyn Trait + 'static>. Write Box<dyn Trait + '_> to hold borrows.
  • dyn Trait is unsized, so it appears behind &, &mut, Box, Rc or Arc.
  • Closures: Box<dyn Fn(i32) -> i32> stores different closures in one slot; a generic F: Fn(i32) -> i32 does not allocate.
  • Supertraits are available through dyn: dyn Pet can call Animal methods, and since Rust 1.86 you can convert &dyn Pet to &dyn Animal.
  • Auto traits: write Box<dyn Trait + Send + Sync> when the value must cross threads.
  • Measure before optimizing. The vtable cost is usually irrelevant compared with allocation or I/O, but it matters in hot inner loops.
  • Enums are a third option when the set of types is closed: a match is static and needs no allocation.