Sub topic 6
Trait objects with dyn Trait
This chapter assumes you can define and implement a trait and write a generic function with a trait bound. Both come from earlier chapters. Here you will learn how Rust lets one variable, vector, or return type hold values of different concrete types, as long as they share a trait.
The problem trait objects solve
A generic function such as fn total<T: Shape>(items: &[T]) is compiled separately for each T. Every element of the slice must have the same concrete type. A Vec<Circle> works, but you can't put a Circle and a Square in the same Vec<T>, because T is a single type.
A trait object removes this limit. The type dyn Shape stands for "some value whose concrete type implements Shape, decided at run time". The compiler no longer knows the concrete type, so it calls methods through a lookup table instead of a direct call. This is dynamic dispatch.
A first example
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. The vector's element type is Box<dyn Shape>. Each Box owns a heap value of some type that implements Shape. The call s.area() runs Circle::area for the first element and Square::area for the second.
Why a pointer is required
dyn Shape is a dynamically sized type. A Circle holds one f64 and a different implementor might hold a whole String, so the compiler can't give dyn Shape a fixed size. You can't store it in a local variable, pass it by value, or put it directly in a Vec. You always use it behind a pointer:
&dyn Shapefor a shared borrow.&mut dyn Shapefor a mutable borrow.Box<dyn Shape>for unique ownership on the heap.Rc<dyn Shape>orArc<dyn Shape>for shared ownership.
What a trait object looks like in memory
A pointer to a trait object is a fat pointer made of two machine words:
- A pointer to the concrete value, such as the
Circle. - A pointer to a vtable for that concrete type and that trait.
The vtable is a static table that the compiler generates for each pair of concrete type and trait. It holds the type's size and alignment, a function that drops the value, and a pointer to each trait method. A call like s.area() loads the function pointer from the vtable and calls it with the data pointer.
You can see the extra word in the size of the pointer:
trait Shape {
fn area(&self) -> f64;
}
struct Circle(f64);
impl Shape for Circle {
fn area(&self) -> f64 {
self.0
}
}
fn main() {
let c = Circle(1.0);
let thin: &Circle = &c;
let fat: &dyn Shape = &c;
println!("{} {}", std::mem::size_of_val(&thin), std::mem::size_of_val(&fat));
}On a 64-bit target this prints 8 16. The plain reference is one word. The trait object reference is two.
Passing and returning trait objects
Use &dyn Trait for a parameter when the function only needs to borrow the value. Use Box<dyn Trait> as a return type when the concrete type depends on run-time data. The next program does both.
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 {
String::from("circle")
}
}
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
fn name(&self) -> String {
String::from("square")
}
}
fn describe(shape: &dyn Shape) -> String {
format!("{} with area {:.2}", shape.name(), shape.area())
}
fn make_shape(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() {
for kind in ["circle", "square", "triangle"] {
match make_shape(kind, 2.0) {
Some(shape) => println!("{}", describe(&*shape)),
None => println!("unknown shape: {kind}"),
}
}
}The output is:
circle with area 12.57
square with area 4.00
unknown shape: trianglemake_shape can't return impl Shape. An impl Trait return type stands for exactly one concrete type, and the two match arms produce different types. Box<dyn Shape> hides the difference. In main, &*shape dereferences the Box and borrows the dyn Shape inside it.
Static versus dynamic dispatch
| Aspect | Generic `T: Shape` | Trait object `dyn Shape` |
|---|---|---|
| Concrete type known | At compile time | At run time only |
| Call cost | Direct call, can be inlined | Indirect call through the vtable |
| Code size | One copy per type used | One copy of the function |
| Mixed types in one collection | No | Yes |
| Value size known | Yes | No, needs a pointer |
Choose generics by default when all values share one type or you need the best speed. Choose dyn Trait when you need a heterogeneous collection, when the type is only known at run time, or when you want to avoid compiling many copies of a function. In most programs the cost of the indirect call is small next to the cost of the work done inside it.
Details that matter
The dyn keyword is required
Since the 2021 edition, writing Box<Shape> is an error. Write Box<dyn Shape>.
Default lifetime bounds
Box<dyn Shape> means Box<dyn Shape + 'static>. The concrete type must not borrow short-lived data. To store a type that holds a reference, write the lifetime out, as in Box<dyn Shape + 'a>. Behind a reference, &'a dyn Shape defaults to dyn Shape + 'a.
Extra marker traits
To move a trait object to another thread, add the marker traits you need, as in Box<dyn Shape + Send>. Plain Box<dyn Shape> makes no promise about Send or Sync, even when the concrete type has them.
Dropping and ownership
When a Box<dyn Shape> goes out of scope, the drop function from the vtable runs, so the concrete value is destroyed correctly and its memory is freed.
Only trait methods are available
Through a dyn Shape you can call only the methods declared in Shape and its supertraits. Inherent methods of Circle are not reachable. To get back to the concrete type you need std::any::Any and a downcast, which is a sign you should consider an enum or another design.
Not every trait qualifies
A trait can be used as dyn Trait only if it is dyn compatible. For example, a method with its own generic type parameter can't be placed in a vtable. The next chapter covers the rules.
Common errors
the size for values of type dyn Shape cannot be known. You useddyn Shapeby value, as inlet s: dyn ShapeorVec<dyn Shape>. Wrap it inBox,&, orRc.expected Circle, found Squarein a match orif. A function returningimpl Shapetried to return two types. ReturnBox<dyn Shape>instead.borrowed value does not live long enoughwith a boxed trait object. The implicit'staticbound rejected a type that holds a reference. Add a lifetime to thedyntype.- A generic function refuses
&dyn Shape. A boundT: Shapeimplicitly requiresT: Sized. WriteT: Shape + ?Sizedto accept trait objects.
Exercise
Why does let shapes = vec![Circle(1.0), Square(2.0)]; fail to compile, and what change to the type of shapes fixes it?
Show answer
A Vec holds elements of one type, and Circle and Square are different types. Declare let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Square(2.0))];. Each element is then a Box<dyn Shape>, a single type that can own either shape.
Exercise
A &dyn Shape is 16 bytes on a 64-bit machine, while &Circle is 8 bytes. What is stored in the extra 8 bytes, and how does it make shape.area() work?
Show answer
The extra word is the vtable pointer. The vtable belongs to the concrete type behind the reference, here Circle. It lists that type's method implementations, so the call loads the address of area from the vtable and calls it with the data pointer.