Sub topic 6
How Dynamic Dispatch Works
This chapter assumes you can define traits, write generic functions with trait bounds, and use Box and references. It also assumes you know that dyn Trait is an unsized type that is used behind a pointer. Here we follow a single method call on a trait object from source code to machine-level behavior, then look at the edge cases that surprise people.
Static and dynamic calls
With a generic function such as fn f<T: Shape>(s: &T), the compiler knows T at each call site. It emits a copy of f for each concrete type, and every s.area() inside that copy names one specific function. This is static dispatch. The target is fixed at compile time, so the compiler can inline it.
With &dyn Shape or Box<dyn Shape>, the concrete type is not part of the type. The compiler compiles s.area() once. At runtime, the program has to find out which area to run. That lookup is dynamic dispatch.
A first example
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String {
String::from("shape")
}
}
struct Circle {
r: f64,
}
struct Rect {
w: f64,
h: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.r * self.r
}
fn name(&self) -> String {
String::from("circle")
}
}
impl Shape for Rect {
fn area(&self) -> f64 {
self.w * self.h
}
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Circle { r: 1.0 }),
Box::new(Rect { w: 2.0, h: 3.0 }),
];
for s in &shapes {
println!("{} {:.2}", s.name(), s.area());
}
}This prints circle 3.14 and then shape 6.00. The loop body contains one s.name() call and one s.area() call, and each resolves to a different function on each iteration. Rect does not override name, so it uses the default method.
The steps of one call
Each Box<dyn Shape> holds two words: a pointer to the value on the heap, and a pointer to a vtable. The vtable is a read-only table the compiler generates for each pair of concrete type and trait. The previous chapter covered its layout. Here is what a call does with it.
- The call site reads the vtable pointer from the fat pointer.
- It loads the function pointer stored at the slot for the method. The slot number is fixed at compile time by the method's position in the trait.
- It calls that function and passes the data pointer as
self.
The call site never looks at the concrete type. It only needs to know that slot N of any Shape vtable holds a function with the signature fn(*const ()) -> f64, roughly speaking.
The cost is one extra load and an indirect call. The indirect call is the larger part of the cost, because the CPU cannot easily predict its target and the compiler cannot inline through it.
Default methods and overrides
The vtable has an entry for every method that is callable on the object, including the ones with default bodies. When Circle overrides name, its vtable entry points at Circle::name. When Rect does not, its entry points at the default body, compiled for Rect. Each type that uses the default gets its own compiled copy of that method, because inside the default body Self is the concrete type. Calls on self inside a default method are therefore statically dispatched, unless Self is unsized.
This is why one dyn Shape call can reach three different pieces of code: an override, a default, or a method from a supertrait. The call site does not care which.
Comparing the two forms
The same function is written below in both styles.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
// Static dispatch: the compiler generates a copy of this function for each concrete type.
fn print_static(s: &impl Shape) {
println!("{}", s.area());
}
// Dynamic dispatch: one compiled function, with the method looked up through a vtable.
fn print_dyn(s: &dyn Shape) {
println!("{}", s.area());
}
fn main() {
let sq = Square(3.0);
print_static(&sq);
print_dyn(&sq);
}| Property | `&impl Shape` | `&dyn Shape` |
|---|---|---|
| Target known at | Compile time | Runtime |
| Copies of the function | One per concrete type | One |
| Inlining of `area` | Possible | Usually not |
| Pointer size | One word | Two words |
| Mixed types in one collection | No | Yes |
The optimizer can sometimes remove the indirection. If print_dyn is inlined into main, the compiler can see that the pointer came from a &Square and call Square::area directly. This is called devirtualization. It is an optimization and not a language guarantee, so do not rely on it.
What you can call on a trait object
A dyn Shape exposes only the methods of Shape and of its supertraits. Inherent methods on Circle, such as a radius() you defined in impl Circle, are not reachable. The type no longer says it is a Circle. To get back to the concrete type you need downcasting, covered in the last chapter.
Methods with generic type parameters cannot get a vtable slot. A vtable has a fixed number of entries, but a generic method would need one entry for every possible type argument. Traits with such methods need special handling, which later chapters cover.
Receivers other than `&self`
A method that takes &self or &mut self works through any pointer. Taking self by value does not work on a trait object, because the size of the value is unknown. One exception is self: Box<Self>, which works because the box can be consumed without moving the unsized value onto the stack.
trait Task {
fn finish(self: Box<Self>) -> String;
}
struct Print(String);
impl Task for Print {
fn finish(self: Box<Self>) -> String {
self.0
}
}
fn main() {
let t: Box<dyn Task> = Box::new(Print(String::from("done")));
println!("{}", t.finish());
}The vtable also records the size and alignment of the concrete type, along with a drop function. This is how Box<dyn Task> frees the right amount of memory with the right destructor when it goes out of scope.
Generic code and `dyn` types
A generic parameter has an implicit Sized bound. A function with T: Shape therefore rejects T = dyn Shape, even though dyn Shape implements Shape. To accept trait objects, relax the bound with ?Sized.
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String {
String::from("shape")
}
}
struct Rect {
w: f64,
h: f64,
}
impl Shape for Rect {
fn area(&self) -> f64 {
self.w * self.h
}
}
fn describe<T: Shape + ?Sized>(s: &T) -> String {
format!("{} {:.1}", s.name(), s.area())
}
fn main() {
let boxed: Box<dyn Shape> = Box::new(Rect { w: 2.0, h: 3.0 });
println!("{}", describe(&*boxed));
println!("{}", describe(&Rect { w: 1.0, h: 1.0 }));
}The first call instantiates describe with T = dyn Shape, and inside it s.area() is a dynamic call. The second instantiates it with T = Rect, and inside it the call is static. One generic function can serve both worlds.
Gotchas
- Name clashes. If two traits implemented by a type both define
name, a call on the concrete type is ambiguous. On adyn Shapethere is no ambiguity, because onlyShape's methods are visible. Call a specific one on a concrete value withShape::name(&x). - Calls through
RcandArc.Rc<dyn Shape>andArc<dyn Shape>dispatch the same way. The pointer is still two words, and the vtable still sits next to the data pointer, not inside the allocation. - Cost in context. An indirect call is cheap relative to allocation, I/O, or locking. It matters in tight loops over small methods, where inlining would otherwise turn the body into a few instructions.
- No runtime type check. The vtable is chosen when the pointer is created, at the unsizing coercion from
Box<Circle>toBox<dyn Shape>. After that, nothing verifies it. The type system guarantees it matches.
Exercise
In let shapes: Vec<Box<dyn Shape>>, which values does the compiler choose at compile time for the call s.area(), and which are chosen at runtime?
Show answer
At compile time the compiler fixes the vtable slot index for area, because it depends only on the method's position in the Shape trait. At runtime, the vtable pointer stored in each fat pointer decides which function sits in that slot, so each element can run a different area. The data pointer is passed as self.
Exercise
Why does fn f<T: Shape>(s: &T) reject &dyn Shape as an argument, and how do you fix it without changing the callers?
Show answer
Every type parameter has an implicit Sized bound, and dyn Shape is unsized. Change the bound to T: Shape + ?Sized. The function is then instantiated with T = dyn Shape and calls through the vtable.