Sub topic 5
Box<dyn Trait>: values of different types behind one interface
This chapter assumes you know traits and generics at a basic level, the ownership rules, and the difference between stack and heap memory. The previous chapters covered Box<T> and recursive types.
The problem: one collection, several types
A Vec<T> holds values of a single type. You may want a list that mixes a Square and a Circle. Both implement the same trait, but they are different types with different sizes.
The compiler must know the size of every value stored inline. Square and Circle could have different sizes, so Vec<Square> cannot also hold a Circle. A generic Vec<T> does not help, because T is still fixed to one type per instance.
Trait objects
A trait object is a value of some unknown concrete type, used only through a trait. You write it as dyn Trait. Its size is not known at compile time, so you cannot hold it directly. You put it behind a pointer, and Box<dyn Trait> is the pointer that owns the value on the heap.
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 main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
for shape in &shapes {
println!("{:.2}", shape.area());
}
}This prints 4.00 and then 3.14. Every element of the Vec is a Box, which has a fixed size, so the vector layout is uniform.
How the call is dispatched
A Box<dyn Shape> is a fat pointer. It holds two addresses: one to the data and one to a vtable. The vtable is a table of function pointers for the concrete type's trait methods. When you call shape.area(), Rust looks up area in the vtable at runtime. This is dynamic dispatch.
Trade-offs
Compare this with a generic function such as fn total<T: Shape>(items: &[T]).
| Approach | Dispatch | Mixed types in one collection | Cost |
|---|---|---|---|
| Generics (`T: Shape`) | Static, resolved at compile time | No | Code is duplicated per type, calls can be inlined |
| `Box<dyn Shape>` | Dynamic, through a vtable | Yes | One heap allocation per value and an indirect call |
Use trait objects when the set of types is open or decided at runtime. Use generics when one type is enough and speed matters.
Common errors
- Forgetting the pointer.
Vec<dyn Shape>fails with a "size cannot be known at compile time" error. Wrap the trait inBox. - Using a trait that is not object safe. A trait with a method that returns
Selfor has generic type parameters cannot be made intodyn Trait. Methods like these need awhere Self: Sizedbound to be excluded. - Assuming
'static.Box<dyn Shape>defaults toBox<dyn Shape + 'static>. If the concrete type holds a short-lived reference, writeBox<dyn Shape + 'a>.
Exercise
Why does Vec<Box<dyn Shape>> compile when Vec<dyn Shape> does not, and what does a call to area() on an element do at runtime?
Show answer
dyn Shape has no size known at compile time, but Box<dyn Shape> is a fat pointer with a fixed size, so the vector can store it. A call to area() follows the vtable pointer in the box to find the concrete type's area function and calls it with the data pointer. This is dynamic dispatch.