Sub topic 5
Box<dyn Trait>: values of different types behind one interface
This chapter assumes you know how traits and generics work at a basic level, and that you know a Vec<T> holds values of one type. You should also know why a Box<T> puts its value on the heap. The goal is to store values of different concrete types in one collection and call the same method on each.
The problem: one collection, several types
A Vec<T> needs every element to be the same type. Suppose you have a Square and a Circle. Both can report an area, but they are different types with different sizes. You cannot write vec![Square(2.0), Circle(1.0)], because the compiler cannot pick one T.
Generics do not help here. A generic function like fn total<T: Shape>(items: &[T]) is still fixed to one concrete T per call. What you need is a way to say "any type that implements Shape", decided while the program runs.
Trait objects
A trait object is a value of unknown concrete type, known only to implement a given trait. You write it as dyn Trait. The dyn keyword marks that method calls on it are resolved at runtime, which is called dynamic dispatch.
dyn Shape has no fixed size, because a Square and a Circle could differ in size. Types without a size known at compile time are called dynamically sized types (DSTs). You cannot store a DST directly in a local variable, a struct field, or a Vec element. You must put it behind a pointer. Box<dyn Shape> is the common choice when you want ownership.
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());
}
}The program prints 4.00 and then 3.14. Each Box::new(...) is coerced from Box<Square> or Box<Circle> to Box<dyn Shape>. The type annotation on shapes tells the compiler which coercion to apply.
What a Box<dyn Trait> contains
A Box<dyn Shape> is a fat pointer, which means it holds two machine words instead of one:
- A pointer to the value on the heap.
- A pointer to a vtable (virtual method table) for the concrete type.
The vtable is created by the compiler for each pair of concrete type and trait. It stores the type's size, its alignment, its drop function, and the address of each trait method. When you call shape.area(), the program looks up area in the vtable and jumps to it.
placeholderThe diagram below shows the layout for the Vec above.
Because the vtable includes drop, dropping a Box<dyn Shape> runs the correct destructor for the hidden concrete type.
Static versus dynamic dispatch
| Aspect | Generics (`T: Shape`) | Trait objects (`dyn Shape`) |
|---|---|---|
| Dispatch | Static, resolved at compile time | Dynamic, through the vtable |
| Code generated | One copy per concrete type (monomorphization) | One copy of the calling code |
| Inlining | Possible | Usually not possible across the call |
| Mixed types in one collection | No | Yes |
| Binary size | Can grow with many types | Smaller |
Prefer generics when all values share one type or you need the fastest path. Choose trait objects when the set of types is open-ended or decided at runtime, such as plugins or a list of UI widgets. The cost of a vtable call is small, so use dyn when it makes the design simpler.
Object safety
Not every trait can become a trait object. A trait must be dyn compatible (older documentation says "object safe"). The main rules are:
- Methods must not return
Self, because the caller cannot know the concrete type. - Methods must not have generic type parameters, because the vtable cannot hold one entry per possible type.
- The trait must not require
Self: Sized.
For example, Clone has fn clone(&self) -> Self, so Box<dyn Clone> does not compile. If you want a method that is excluded from the vtable, add where Self: Sized to that method. The rest of the trait stays usable as an object.
trait Describe {
fn name(&self) -> String;
fn boxed_copy(&self) -> Self
where
Self: Sized;
}
struct Dog;
impl Describe for Dog {
fn name(&self) -> String {
String::from("dog")
}
fn boxed_copy(&self) -> Self {
Dog
}
}
fn main() {
let pets: Vec<Box<dyn Describe>> = vec![Box::new(Dog)];
for pet in &pets {
println!("{}", pet.name());
}
}This compiles because boxed_copy opts out of the vtable. You cannot call boxed_copy on a dyn Describe, but you can call it on a Dog.
Lifetimes and the implicit 'static bound
Box<dyn Shape> in a type position means Box<dyn Shape + 'static>. That requires the concrete type to contain no non-static borrowed references. If your type holds a reference, you must say so:
trait Label {
fn text(&self) -> &str;
}
struct Title<'a>(&'a str);
impl<'a> Label for Title<'a> {
fn text(&self) -> &str {
self.0
}
}
fn main() {
let owned = String::from("Chapter");
let labels: Vec<Box<dyn Label + '_>> = vec![Box::new(Title(&owned))];
for label in &labels {
println!("{}", label.text());
}
}The + '_ lets the boxed value borrow from owned. Without it, the compiler reports that owned does not live long enough for a 'static object.
Common errors
- "the size for values of type
dyn Shapecannot be known": you useddyn Shapewithout a pointer. Wrap it inBox,&, orRc. - "the trait cannot be made into an object": the trait has a method returning
Selfor a generic method. Redesign it, or addwhere Self: Sizedto that method. - "expected
Box<dyn Shape>, foundBox<Square>" in avec!: the compiler could not infer the coercion. Add a type annotation to the binding. - Cannot call a type's own methods: a
Box<dyn Shape>exposes only the trait's methods. If you need to get the concrete type back, add anas_anymethod that returns&dyn Anyand usedowncast_ref. - Forgetting
+ 'a: boxed values that borrow data need an explicit lifetime bound.
Exercises
Exercise
Why can you not write let s: dyn Shape = Square(2.0);, and what is the smallest change that makes the idea work?
Show answer
dyn Shape is a dynamically sized type, so the compiler cannot know how much stack space a local variable needs. Put it behind a pointer, for example let s: Box<dyn Shape> = Box::new(Square(2.0)); or let s: &dyn Shape = &Square(2.0);.
Exercise
A trait has the method fn duplicate(&self) -> Self;. Why does Vec<Box<dyn MyTrait>> fail to compile, and how can you keep the trait usable as an object?
Show answer
Returning Self makes the trait not dyn compatible, since the vtable cannot describe a return type that depends on the hidden concrete type. Add where Self: Sized to duplicate. The method is then left out of the vtable and the trait can be used as dyn MyTrait, though duplicate cannot be called through the object.