Sub topic 6
How dynamic dispatch works
This chapter assumes you know how to define traits, write generic functions with trait bounds, and take references in Rust. It also assumes you have seen &dyn Trait and Box<dyn Trait> written down. Here you will see what happens when a method is called through one of them.
The problem dynamic dispatch solves
With generics, the compiler knows the concrete type at every call site. It generates a copy of the function for each type (monomorphization) and calls the right method directly. This is static dispatch.
A &dyn Shape has no concrete type known at compile time. The function body is compiled once, so the call to s.area() cannot be wired to a fixed address. The right method has to be found while the program runs. That lookup is dynamic dispatch.
A call, step by step
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
struct Circle(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.0 * self.0
}
}
fn print_dyn(s: &dyn Shape) {
println!("{:.2}", s.area());
}
fn main() {
print_dyn(&Square(3.0));
print_dyn(&Circle(1.0));
}This prints 9.00 and then 3.14. There is one compiled print_dyn, yet it runs two different area implementations.
The two calls in main each perform an unsizing coercion. A &Square becomes a &dyn Shape. The compiler builds a fat pointer, which holds two values:
- A data pointer to the
SquareorCirclevalue. - A vtable pointer to a table generated for the pair (
Square,Shape) or (Circle,Shape).
Inside print_dyn, the call s.area() compiles to these steps:
- Read the vtable pointer from the fat pointer.
- Load the function pointer for
areafrom a fixed slot in that table. - Call it, passing the data pointer as
&self.
The slot position is known at compile time, because the trait defines the method order. Only the table contents differ by type.
What the vtable holds
A vtable is a static table, created once per (type, trait) pair. It typically contains:
- A function that drops the value.
- The size and alignment of the concrete type.
- One function pointer for each dyn-callable method, including supertrait methods.
The drop entry and the size are why Box<dyn Shape> can free its memory correctly without knowing the type.
Costs
Dynamic dispatch costs a little at each call:
- One extra pointer load, then an indirect call.
- The compiler usually cannot inline across the call, since the target is unknown. This often matters more than the load.
- The fat pointer is twice the size of a thin pointer.
For code that is not in a hot loop, these costs are rarely measurable. They matter in tight numeric loops, where static dispatch lets the optimizer inline and vectorize.
Common mistakes
- Expecting a method to be chosen by the static type of a variable. With
dyn, the choice follows the concrete value behind the pointer. - Assuming
&dyn Shapeis one pointer wide. It is two, so it cannot be cast to a thin pointer without losing the vtable. - Assuming dynamic dispatch means a heap allocation. A
&dyn Shapeto a stack value allocates nothing. OnlyBox<dyn Shape>does.
Exercise
In the call s.area() where s is &dyn Shape, which part of the fat pointer decides which implementation runs, and which part becomes &self?
Show answer
The vtable pointer decides which implementation runs, because the area function pointer is loaded from the vtable. The data pointer becomes &self and is passed to that function.