Sub topic 2
How dynamic dispatch works
Assume you know Rust ownership, borrowing, structs, traits, generics, and Box. Dynamic dispatch means Rust chooses the method implementation at runtime instead of fixing it entirely at compile time.
How dynamic dispatch works
A trait object is written as dyn Trait. It is unsized, so it must be used behind a pointer such as &dyn Trait or Box<dyn Trait>. The pointer contains a data pointer and a vtable pointer. A vtable stores function pointers for the concrete type's trait methods.
When shape.area() runs, Rust follows the vtable to select the correct implementation.
Mixed types with `Vec<Box<dyn Trait>>`
A vector normally contains one concrete type. Trait objects allow different types that implement the same trait:
trait Shape {
fn area(&self) -> f64;
}
struct Circle(f64);
struct Rect(f64, f64);
impl Shape for Circle {
fn area(&self) -> f64 { std::f64::consts::PI * self.0 * self.0 }
}
impl Shape for Rect {
fn area(&self) -> f64 { self.0 * self.1 }
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Circle(1.0)),
Box::new(Rect(2.0, 3.0)),
];
for shape in &shapes {
println!("{:.2}", shape.area());
}
}Generics, `impl Trait`, or `dyn Trait`?
Generics and impl Trait use static dispatch. The compiler creates specialized code for each concrete type. This is usually faster, but one collection cannot contain several concrete types.
Use dyn Trait when the concrete type is selected at runtime, or when a heterogeneous collection matters.
| Choice | Dispatch | Typical use |
|---|---|---|
| `T: Trait` | Static | Performance and known types |
| `impl Trait` | Static | Simple function interfaces |
| `dyn Trait` | Dynamic | Runtime-selected or mixed types |
Closures as `dyn Fn`
Each closure has a different anonymous type. Boxing them behind dyn Fn gives one common type:
fn make_operation(double: bool) -> Box<dyn Fn(i32) -> i32> {
if double {
Box::new(|x| x * 2)
} else {
Box::new(|x| x + 1)
}
}
fn main() {
let operation = make_operation(true);
println!("{}", operation(5));
}Exercise
Why can Vec<Box<dyn Shape>> contain both Circle and Rect?
Show answer
Each value is boxed behind the shared Shape interface, so the vector stores one pointer type while the vtable selects each concrete implementation.