Sub topic 7
Vec<Box<dyn Trait>> and mixed types
This chapter assumes you know how to define a trait, implement it for structs, and use Box. It also assumes you know that dyn Trait is an unsized type that must sit behind a pointer.
The problem: one Vec, several types
A Vec<T> stores one type T. Every element must have the same size and layout. Suppose you have a Circle and a Rect that both implement Shape. A Vec<Circle> cannot hold a Rect, and a generic Vec<T> where T: Shape still fixes one concrete T per vector.
A trait object removes that limit. Vec<Box<dyn Shape>> holds values of any type that implements Shape.
Why Box is needed
dyn Shape has no fixed size, because a Circle and a Rect take different amounts of memory. A Vec needs elements of equal size. Box<dyn Shape> is a fat pointer, a data pointer plus a vtable pointer, and it is always 16 bytes on a 64-bit target. The Vec stores these equal-sized pointers. The actual values live on the heap.
A working 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. Three details matter here.
- The annotation
Vec<Box<dyn Shape>>is required. Without it,vec!would inferBox<Circle>from the first element and reject the second. - Each
Box::new(...)is coerced fromBox<Circle>toBox<dyn Shape>. This is an unsizing coercion, and it happens at the point where the target type is known. Rectdoes not overridename, so the call uses the default method. The vtable forRectpoints at that default.
Common errors
- Forgetting the annotation. You get a type mismatch on the second element. Add the
Vec<Box<dyn Trait>>type to the binding. - Using
Vec<dyn Shape>. The compiler reports that the size is not known at compile time. Wrap each element in aBox. - Cloning the vector.
Box<dyn Shape>is notCloneunless you add that support yourself.Cloneis not dyn compatible becauseclonereturnsSelf. - Assuming you can see the concrete type. Through
dyn Shapeyou can call onlyShapemethods. Fields such asrare not reachable.
Costs to keep in mind
Each element costs one heap allocation, and each call goes through the vtable. This is usually acceptable. In a hot loop over millions of items, a generic function or an enum of known variants can be faster. A later chapter compares these options.
Exercise
Why does let v = vec![Box::new(Circle { r: 1.0 }), Box::new(Rect { w: 1.0, h: 2.0 })]; fail to compile, and what is the smallest fix?
Show answer
Without an annotation, vec! infers the element type Box<Circle> from the first item, and Box<Rect> does not match. The fix is to annotate the binding as Vec<Box<dyn Shape>>. The compiler then coerces each Box<Circle> and Box<Rect> to Box<dyn Shape>.