Sub topic 7
Vec<Box<dyn Trait>> and Mixed Types
This chapter assumes you know how to define a trait and implement it for a struct, and that you have used Box and references. You should also know that a dyn Trait value is unsized and must sit behind a pointer. The previous chapters covered fat pointers, vtables and how a call is resolved at runtime. Here you will use them to build collections that hold different concrete types.
Why a plain Vec is not enough
A Vec<T> stores elements of one type T. The elements are laid out back to back, so every element must have the same size. A Circle with one f64 and a Rect with two f64 fields are different types of different sizes. A Vec<Circle> cannot hold a Rect.
A trait object removes the size problem. dyn Shape has no fixed size, but a pointer to it does. A Box<dyn Shape> is always two machine words: a data pointer and a vtable pointer. Every element of a Vec<Box<dyn Shape>> therefore has the same size, whatever it points to.
Building the collection
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. Rect does not override name, so the default method runs. The loop calls the same two methods on every element. Each call goes through the vtable of the element's concrete type.
The type annotation does the conversion
The annotation Vec<Box<dyn Shape>> is what makes the example compile. Each Box::new(Circle { .. }) has type Box<Circle>. The compiler converts it to Box<dyn Shape> through an unsized coercion, and that happens only where the expected type is known.
If you write vec![Box::new(Circle { r: 1.0 }), Box::new(Rect { w: 1.0, h: 1.0 })] with no annotation, the compiler infers the element type from the first item. It then reports a mismatched types error on the second item. Fix this by annotating the binding, by annotating a function return type, or by casting the first element with as Box<dyn Shape>.
Mutating elements
Elements are owned by the Vec, so you can borrow them mutably. Methods that take &mut self work through iter_mut, and each element gets its own implementation:
trait Counter {
fn tick(&mut self);
fn value(&self) -> u32;
}
struct Up(u32);
struct Down(u32);
impl Counter for Up {
fn tick(&mut self) {
self.0 += 1;
}
fn value(&self) -> u32 {
self.0
}
}
impl Counter for Down {
fn tick(&mut self) {
self.0 = self.0.saturating_sub(1);
}
fn value(&self) -> u32 {
self.0
}
}
fn main() {
let mut counters: Vec<Box<dyn Counter>> = vec![Box::new(Up(0)), Box::new(Down(5))];
for c in counters.iter_mut() {
c.tick();
c.tick();
}
for c in &counters {
println!("{}", c.value());
}
}This prints 2 and then 3. In the first loop c has type &mut Box<dyn Counter>, and auto-dereferencing finds tick on the trait object.
You can also call a method that consumes self on a boxed trait object, but only if the trait declares it as fn consume(self: Box<Self>). A plain fn consume(self) cannot be called on dyn Trait, because the compiler does not know the value's size.
Choosing behavior at runtime
The main use of Vec<Box<dyn Trait>> is to build the contents from data you only see at runtime, such as a config file, user input or a network message. A factory function returns a boxed trait object:
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String;
}
struct Circle(f64);
struct Square(f64);
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.0 * self.0
}
fn name(&self) -> String {
"circle".to_string()
}
}
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
fn name(&self) -> String {
"square".to_string()
}
}
fn make(kind: &str, size: f64) -> Option<Box<dyn Shape>> {
match kind {
"circle" => Some(Box::new(Circle(size))),
"square" => Some(Box::new(Square(size))),
_ => None,
}
}
fn main() {
let input = [("circle", 1.0), ("square", 2.0), ("hexagon", 1.0), ("square", 1.0)];
let mut shapes: Vec<Box<dyn Shape>> = input
.iter()
.filter_map(|(kind, size)| make(kind, *size))
.collect();
shapes.sort_by(|a, b| a.area().partial_cmp(&b.area()).unwrap());
for s in &shapes {
println!("{} {:.2}", s.name(), s.area());
}
}The output is:
square 1.00
circle 3.14
square 4.00The unknown "hexagon" is dropped by filter_map. Each match arm has a different concrete type, and the declared return type Option<Box<dyn Shape>> coerces each one. Sorting works because it only needs the trait's methods.
Other pointer types in a collection
Box is the default because it owns its value. The same idea works with other pointers, and the choice depends on who owns the data:
| Collection type | Ownership | Use when |
|---|---|---|
| `Vec<Box<dyn T>>` | The Vec owns each value uniquely. | The collection is the only owner. |
| `Vec<&dyn T>` | Values live elsewhere and are borrowed. | Values already exist as locals or fields, and you want a short-lived view. |
| `Vec<Rc<dyn T>>` | Shared ownership on one thread. | Several collections or structures point to the same object. |
| `Vec<Arc<dyn T>>` | Shared ownership across threads. | Sharing is needed across threads. The trait needs `Send + Sync` bounds. |
Vec<&dyn T> has no heap allocation per element. The elements are fat pointers to values you keep alive yourself, and the borrow checker enforces that they outlive the Vec. Cloning an Rc<dyn T> copies the fat pointer and increments the count, without touching the value.
What you cannot do with the elements
Erasing the type removes some abilities. These are the most common stumbling blocks.
- Clone.
ClonereturnsSelf, so it is not dyn compatible, andBox<dyn Shape>is notClone. A common workaround is a trait methodfn box_clone(&self) -> Box<dyn Shape>that each implementor writes. - Compare.
PartialEqtakesSelfas a type parameter default, so you cannot compare twodyn Shapevalues with==. Compare through trait methods such asarea. - Generic methods. A method with its own type parameter cannot be in the vtable. The
where Self: Sizedopt-out, covered later in this tutorial, leaves it callable only on concrete types. - Access to fields. Through the trait object you see only the trait's methods. Recovering the concrete type needs
dyn Any, which a later chapter covers. - Moving a value out.
let v: dyn Shape = *boxed;fails because the value is unsized. Use the box, a reference, or aself: Box<Self>method.
Costs and alternatives
Each Box is a separate heap allocation, and every call goes through a pointer and an indirect jump. A loop over thousands of small objects therefore has worse cache behavior than a Vec<Circle>. The indirect call also usually prevents inlining. For most programs this does not matter, but it can in a hot loop.
If the full set of types is known and closed, an enum is an alternative:
| Question | `Vec<Box<dyn Trait>>` | `Vec<MyEnum>` |
|---|---|---|
| Can downstream code add new types? | Yes | No, variants are fixed in one place. |
| Memory per element | Pointer plus a heap allocation | Size of the largest variant, inline |
| Adding an operation | Add a trait method and update every implementor | Add one `match` function |
| Adding a type | Write a new `impl` | Add a variant and update every `match` |
| Exhaustiveness checked by compiler | No | Yes |
Choose trait objects when the set of types is open, for example plugins or user-supplied handlers. Choose an enum when the set is closed and you want exhaustive checking.
Exercise
You write let items = vec![Box::new(Circle { r: 1.0 }), Box::new(Rect { w: 1.0, h: 2.0 })]; and the compiler reports a type mismatch. Why does the version with the annotation let items: Vec<Box<dyn Shape>> = vec![...] compile, and what is stored in each slot of the Vec?
Show answer
Without an annotation, the compiler infers the element type Box<Circle> from the first item, so Box<Rect> does not fit. With the annotation, the expected element type is Box<dyn Shape>. Each Box::new(...) is then converted by an unsized coercion. Each slot holds a fat pointer of two words, a data pointer to the heap value and a pointer to the vtable for that value's concrete type. All slots have the same size even though the pointed-to types differ.
Exercise
A teammate wants Vec<Box<dyn Shape>> to support .clone() on the whole Vec. Why does it not compile, and what is one way to provide it?
Show answer
Clone::clone returns Self, which is not dyn compatible, so Box<dyn Shape> does not implement Clone. One fix is to add a method fn box_clone(&self) -> Box<dyn Shape> to the trait, implement it in each concrete type by cloning self and boxing it, and then implement Clone for Box<dyn Shape> by calling box_clone.