Sub topic 6
Trait Objects with dyn Trait
This chapter assumes you can write a trait, implement it for a type, and use a trait bound on a generic function. Generic bounds fix one concrete type per call. A trait object lets one collection or field hold different types that share a trait.
The problem generics do not solve
A Vec<T> holds a single type T. You cannot put a Circle and a Square in the same Vec<T>, even if both implement Shape. A trait object solves this by erasing the concrete type and keeping only the trait's interface.
Writing a trait object
The type dyn Shape means "some type that implements Shape". Its size is not known at compile time, so you always use it behind a pointer, such as &dyn Shape, Box<dyn Shape>, or Rc<dyn Shape>.
trait Shape {
fn area(&self) -> f64;
}
struct Circle(f64);
struct Square(f64);
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.0 * self.0
}
}
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Square(2.0))];
let total: f64 = shapes.iter().map(|s| s.area()).sum();
println!("{total:.2}");
}This prints 7.14. Each Box::new(...) is coerced from Box<Circle> or Box<Square> to Box<dyn Shape> because the annotation on shapes asks for it.
How dynamic dispatch works
A pointer to a trait object is a fat pointer. It holds two addresses:
- a pointer to the value's data
- a pointer to a vtable, a table of function pointers for that type's
Shapemethods
When you call s.area(), the program looks up area in the vtable and jumps to it. This is dynamic dispatch, because the target is chosen at run time.
Static versus dynamic dispatch
| Aspect | Generic `T: Shape` | `dyn Shape` |
|---|---|---|
| Dispatch | Static, resolved at compile time | Dynamic, through the vtable |
| Code generated | One copy per concrete type | One copy of the calling code |
| Mixed types in one `Vec` | No | Yes |
| Inlining | Possible | Usually not |
| Pointer needed | No | Yes |
Choose generics when the types are known at compile time and speed matters. Choose dyn when the set of types is open or decided at run time, such as plugins or heterogeneous lists.
Common errors
- Using
dyn Shapewithout a pointer.Vec<dyn Shape>fails with "the size for values of typedyn Shapecannot be known". UseVec<Box<dyn Shape>>. - Forgetting the coercion site.
vec![Box::new(Circle(1.0)), Box::new(Square(2.0))]with no type annotation fails, because the compiler infersBox<Circle>from the first element. - Using a trait that is not dyn compatible. Traits with generic methods or methods returning
Selfcannot be made into objects. The next chapter covers the rules.
Exercise
Why can you write Vec<Box<dyn Shape>> but not Vec<dyn Shape>?
Show answer
dyn Shape has no size known at compile time, because the concrete type behind it can vary. A Vec needs elements of a fixed size. Box<dyn Shape> has a fixed size, since it is a fat pointer made of a data address and a vtable address.
Exercise
A function takes items: &[Box<dyn Shape>]. Does calling item.area() on each element use static or dynamic dispatch?
Show answer
Dynamic dispatch. The concrete type of each element is not known at compile time, so the call goes through the vtable.