Blog

Part 21 · Trait Objects in Rust: dyn, vtables and Dynamic Dispatch

A Vec holds one type, so how do you keep circles and squares in the same list? This part covers dyn Trait, the fat pointer and vtable behind it, static vs dynamic dispatch, and which traits can be used with dyn.

Generics let one function work with many types, but each call still picks one type. A Vec<T> holds only Ts. So how do you keep a circle and a square in the same list, and call area on each one? The answer is a trait object, written dyn Shape.

This part covers Box<dyn Trait> and &dyn Trait, the two-pointer value behind them, the table of functions that makes the call work, when to choose dyn over generics, and which traits can be used with dyn at all. It builds on traits from Part 14, generics from Part 15 and Box from Part 20. Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

Both types implement Shape, and the loop only calls Shape methods. Will it compile?

use std::f64::consts::PI;

trait Shape {
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

struct Square {
    side: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        PI * self.radius * self.radius
    }
}

impl Shape for Square {
    fn area(&self) -> f64 {
        self.side * self.side
    }
}

fn main() {
    let shapes = vec![Circle { radius: 1.0 }, Square { side: 2.0 }];
    for shape in &shapes {
        println!("{:.2}", shape.area());
    }
}

It doesn’t:

error[E0308]: mismatched types
  --> src/main.rs:28:47
   |
28 |     let shapes = vec![Circle { radius: 1.0 }, Square { side: 2.0 }];
   |                                               ^^^^^^^^^^^^^^^^^^^^ expected `Circle`, found `Square`

The first item told the compiler that this is a Vec<Circle>. The second item is a Square, which is a different type. It doesn’t matter that both implement Shape. A Vec<T> has one T, and every item in it is that T.

Why generics can’t fix this

Part 15’s tool for “any type that implements a trait” was a generic. Here is the first line of one, which we’ll write in full later in this part:

fn total_static<T: Shape>(shapes: &[T]) -> f64

That works for a slice of circles, or a slice of squares. It doesn’t work for a slice of both. T is still one type per call. The compiler makes one copy of total_static for circles and another for squares, and each copy knows exactly which area to call and how big each item is.

A mixed list needs two things the compiler can’t know up front: how big each item is, and which area to run for it. Both have to be found out while the program runs. That’s what a trait object does.

Box<dyn Shape>: a list of different shapes

dyn Shape means “some type that implements Shape, decided at run time”. You always use it behind a pointer, such as a Box:

use std::f64::consts::PI;

trait Shape {
    fn name(&self) -> &str;
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

struct Square {
    side: f64,
}

impl Shape for Circle {
    fn name(&self) -> &str {
        "circle"
    }
    fn area(&self) -> f64 {
        PI * self.radius * self.radius
    }
}

impl Shape for Square {
    fn name(&self) -> &str {
        "square"
    }
    fn area(&self) -> f64 {
        self.side * self.side
    }
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle { radius: 1.0 }),
        Box::new(Square { side: 2.0 }),
        Box::new(Circle { radius: 0.5 }),
    ];
    let mut total = 0.0;
    for shape in &shapes {
        println!("{} has area {:.2}", shape.name(), shape.area());
        total += shape.area();
    }
    println!("total {total:.2}");
}

It prints:

circle has area 3.14
square has area 4.00
circle has area 0.79
total 7.93

Now every item has the same type, Box<dyn Shape>. Each box holds a different concrete type, and each call to area runs the right one.

Box::new(Circle { .. }) makes a Box<Circle>. The compiler turns it into a Box<dyn Shape> because the type on shapes asks for one, and Circle implements Shape. This is a coercion: a conversion the compiler does for you without a cast. Leave the type off shapes, and the compiler sees a Box<Circle> first and a Box<Square> second, and you get E0308 again.

&dyn Shape works too

A Box owns the value. When you only need to look at a shape, borrow it as &dyn Shape:

use std::f64::consts::PI;

trait Shape {
    fn name(&self) -> &str;
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

struct Square {
    side: f64,
}

impl Shape for Circle {
    fn name(&self) -> &str {
        "circle"
    }
    fn area(&self) -> f64 {
        PI * self.radius * self.radius
    }
}

impl Shape for Square {
    fn name(&self) -> &str {
        "square"
    }
    fn area(&self) -> f64 {
        self.side * self.side
    }
}

fn describe(shape: &dyn Shape) {
    println!("a {} with area {:.2}", shape.name(), shape.area());
}

fn main() {
    let c = Circle { radius: 1.0 };
    let s = Square { side: 3.0 };
    describe(&c);
    describe(&s);

    let both: [&dyn Shape; 2] = [&c, &s];
    let total: f64 = both.iter().map(|shape| shape.area()).sum();
    println!("total {total:.2}");
}

It prints:

a circle with area 3.14
a square with area 9.00
total 12.14

describe is one function, compiled once. It isn’t generic, so the compiler doesn’t make a copy for circles and another for squares. The same machine code runs for both, and it finds the right area while it runs. We’ll see how in a moment.

Why dyn needs a pointer

Try to take a dyn Shape by value:

use std::f64::consts::PI;

trait Shape {
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        PI * self.radius * self.radius
    }
}

fn show(shape: dyn Shape) {
    println!("{:.2}", shape.area());
}

fn main() {
    show(Circle { radius: 1.0 });
}

It prints:

error[E0277]: the size for values of type `(dyn Shape + 'static)` cannot be known at compilation time
  --> src/main.rs:17:16
   |
17 | fn show(shape: dyn Shape) {
   |                ^^^^^^^^^ doesn't have a size known at compile-time
...
help: function arguments must have a statically known size, borrowed types always have a known size
   |
17 | fn show(shape: &dyn Shape) {
   |                +

A Circle here is 8 bytes. A rectangle with a width and a height would be 16, and a shape that holds a String would be bigger again. “Some type that implements Shape” has no single size, so the compiler can’t reserve space for it on the stack. A pointer always has a known size, so &dyn Shape and Box<dyn Shape> are fine. The + 'static in the message is a default the compiler fills in, which Part 25 explains. For now, read it as “a dyn Shape that doesn’t borrow anything”.

The help: line gives both fixes. Take &dyn Shape to borrow, or take impl Shape to make the function generic, as in Part 15.

A fat pointer: two addresses in one

If the pointer is the only thing the compiler knows about, how does a call find the right area? Measure the pointers:

use std::mem::size_of;

trait Shape {
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        self.radius * self.radius * 3.0
    }
}

fn main() {
    println!("&Circle:        {} bytes", size_of::<&Circle>());
    println!("&dyn Shape:     {} bytes", size_of::<&dyn Shape>());
    println!("Box<Circle>:    {} bytes", size_of::<Box<Circle>>());
    println!("Box<dyn Shape>: {} bytes", size_of::<Box<dyn Shape>>());
    let c = Circle { radius: 1.0 };
    println!("area {}", c.area());
}

It prints:

&Circle:        8 bytes
&dyn Shape:     16 bytes
Box<Circle>:    8 bytes
Box<dyn Shape>: 16 bytes
area 3

On a 64-bit machine, a pointer to a Circle is 8 bytes: one address. A pointer to a dyn Shape is 16 bytes: two addresses. That’s called a fat pointer. You’ve met one before: a slice &[i32] in Part 4 was a pointer and a length. A trait object is a pointer and a second pointer:

  • the data pointer leads to the value itself, the Circle;
  • the vtable pointer leads to a small table of facts and functions for “Circle as a Shape“.

The vtable

“Vtable” is short for virtual method table, a name from C++. The compiler builds one vtable for each pair of a type and a trait that you use with dyn: one for Circle as a Shape, one for Square as a Shape. It builds them while compiling, and they’re stored in the program file, next to the code. Nothing is built at run time, and nobody owns a vtable, so it’s never freed.

Each vtable holds, in this order in rustc today:

  1. drop: the code that drops a value of this type, fields and all, as in Part 6. A Box<dyn Shape> needs it, because it has to free a value without knowing its type.
  2. size and align: how many bytes the value takes, and the alignment the type needs. A Box needs these to give the memory back.
  3. the trait’s methods, one slot each: here, the address of Circle::area.

The exact layout is an internal detail of the compiler. The language doesn’t promise it, and you never read a vtable yourself. But the idea, a data pointer plus a pointer to a table of functions, is how every dyn call works, and it hasn’t changed in practice.

So shapes[i].area() turns into: read the vtable pointer, read the area slot of that vtable, and call the function there with the data pointer as self. Here are two calls, one on a circle and one on a square:

shapes[0] Circle's vtable code data vtable drop size 8 align 8 area Circle::area on the heap Circle { radius: 1.0 } self shapes[1] Square's vtable data vtable drop size 8 align 8 area Square::area on the heap Square { side: 2.0 } self shapes[0] = (data pointer, vtable pointer) Circle's vtable: drop, size, align, then the methods the area slot holds the address of Circle::area Circle::area runs with self = the Circle: 3.14 same line of code, Square's vtable: 4.00 shapes[0].area(): read the fat pointer, two addresses follow the vtable pointer to Circle's vtable pick the area slot and read the function address in it jump to Circle::area, passing the data pointer as self shapes[1].area(): the same steps lead to Square::area

A call through a trait object reads the vtable pointer, takes the method’s address from the vtable, and calls it with the data pointer as self. A different type means a different vtable, so the same line runs a different function.

Here are those steps in words, in case the animation doesn’t play for you:

  1. shapes[0].area() starts by reading shapes[0], a fat pointer: a data pointer and a vtable pointer. The data pointer owns the Circle on the heap, because it’s a Box.
  2. The call follows the vtable pointer to Circle’s vtable. It holds drop, the size (8), the alignment (8) and one slot per method, here just area. The vtable pointer is drawn dashed, like a shared borrow, because it only points at the table and owns nothing.
  3. The call picks the area slot. The compiler knows which slot area is, because it built every Shape vtable with the same order. The slot holds the address of the function Circle::area.
  4. The call jumps to Circle::area and passes the data pointer as self. self is a &Circle now, so the function reads the radius and returns 3.14.
  5. shapes[1].area() runs the same machine code. This time the vtable pointer leads to Square’s vtable, whose area slot holds Square::area, so it returns 4.00.

We can see the size, alignment and drop entries at work. size_of_val and align_of_val take a reference to any value and, for a dyn, read the answer from its vtable. Dropping a Box<dyn Shape> runs the right drop through the vtable too:

use std::mem::{align_of_val, size_of_val};

trait Shape {
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

struct Tile {
    side: u8,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        self.radius * self.radius * 3.0
    }
}

impl Shape for Tile {
    fn area(&self) -> f64 {
        f64::from(self.side) * f64::from(self.side)
    }
}

impl Drop for Circle {
    fn drop(&mut self) {
        println!("drop Circle with radius {}", self.radius);
    }
}

impl Drop for Tile {
    fn drop(&mut self) {
        println!("drop Tile with side {}", self.side);
    }
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> =
        vec![Box::new(Circle { radius: 2.0 }), Box::new(Tile { side: 3 })];
    for shape in &shapes {
        let value: &dyn Shape = shape.as_ref();
        println!(
            "size {}, align {}, area {}",
            size_of_val(value),
            align_of_val(value),
            value.area()
        );
    }
    drop(shapes);
    println!("the Vec is gone");
}

It prints:

size 8, align 8, area 12
size 1, align 1, area 9
drop Circle with radius 2
drop Tile with side 3
the Vec is gone

Both calls to size_of_val pass a &dyn Shape, and still get different answers: 8 bytes for the Circle and 1 for the Tile. That number came from each value’s vtable. When the Vec was dropped, each box ran its own type’s drop, found the same way.

Static or dynamic dispatch

Picking which function a call runs is called dispatch. Rust gives you two kinds:

  • Static dispatch is generics and impl Trait, from Part 15. The compiler knows the type at each call, so it calls the function directly. It makes one copy of the generic code per type.
  • Dynamic dispatch is dyn Trait. The type is found at run time, through the vtable. One copy of the code serves every type.

Here is the same sum written both ways:

use std::any::type_name;

trait Shape {
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

struct Square {
    side: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        self.radius * self.radius * 3.0
    }
}

impl Shape for Square {
    fn area(&self) -> f64 {
        self.side * self.side
    }
}

fn total_static<T: Shape>(shapes: &[T]) -> f64 {
    let short = type_name::<T>().rsplit("::").next().unwrap_or("?");
    println!("total_static::<{short}>");
    shapes.iter().map(|s| s.area()).sum()
}

fn total_dynamic(shapes: &[Box<dyn Shape>]) -> f64 {
    println!("total_dynamic, one copy for every type");
    shapes.iter().map(|s| s.area()).sum()
}

fn main() {
    let circles = [Circle { radius: 1.0 }, Circle { radius: 2.0 }];
    let squares = [Square { side: 2.0 }];
    println!("{}", total_static(&circles));
    println!("{}", total_static(&squares));

    let mixed: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle { radius: 1.0 }),
        Box::new(Square { side: 2.0 }),
    ];
    println!("{}", total_dynamic(&mixed));
}

It prints:

total_static::<Circle>
15
total_static::<Square>
4
total_dynamic, one copy for every type
7

type_name gives the full path of a type, such as my_project::Circle, so we keep only the part after the last ::. total_static was compiled twice, once per type. total_dynamic was compiled once, and it’s the only one of the two that can take a mixed list.

What each costs:

  • A dyn call is one indirect call. The CPU loads an address from the vtable and jumps to it. On its own that’s cheap, and in most programs you won’t be able to measure it.
  • A dyn call can’t be inlined. With static dispatch, the optimiser can copy a small method like area into the loop and optimise both together. Through a vtable, it doesn’t know which function will run, so it can’t. In a hot loop over millions of small items, this is the part that costs.
  • Generics make more code. Each type adds a copy, which grows the program and the build time. dyn keeps one copy.
  • dyn usually needs a Box, which is a heap allocation per item, unless you can borrow with &dyn.

The rule of thumb: use generics by default. Use dyn when the set of types is only known at run time, when one collection must hold several types, or when you want to keep the code small and the cost of a call through a table doesn’t matter. A plugin list, a set of event handlers, or an error from “something that went wrong” are all good fits.

If you know every type ahead of time and there are only a few, an enum from Part 11 is a third option. It holds different shapes in one Vec with no heap allocation and no vtable. The cost is that adding a new shape means editing the enum.

Dyn compatibility: not every trait can be dyn

A vtable has one slot per method, and each slot holds the address of one function. Some methods can’t fit in a slot like that. Here, a generic method:

trait Shape {
    fn area(&self) -> f64;
    fn scaled<T: Into<f64>>(&self, by: T) -> f64;
}

struct Circle {
    radius: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        self.radius * self.radius * 3.0
    }
    fn scaled<T: Into<f64>>(&self, by: T) -> f64 {
        self.area() * by.into()
    }
}

fn main() {
    let shape: Box<dyn Shape> = Box::new(Circle { radius: 1.0 });
    println!("{}", shape.area());
}

It prints:

error[E0038]: the trait `Shape` is not dyn compatible
...
note: for a trait to be dyn compatible it needs to allow building a vtable
...
1 | trait Shape {
  |       ----- this trait is not dyn compatible...
2 |     fn area(&self) -> f64;
3 |     fn scaled<T: Into<f64>>(&self, by: T) -> f64;
  |        ^^^^^^ ...because method `scaled` has generic type parameters
  = help: consider moving `scaled` to another trait

A generic method isn’t one function. It’s a family of copies, one for each T that anyone uses, and the compiler only makes the copies it sees called. A vtable built while compiling can’t hold a slot for every possible T. So Rust refuses dyn Shape for this trait. This rule used to be called object safety, and you’ll still see that name in older books and posts. The compiler and the Rust Reference now call it dyn compatibility.

The main things that make a trait not dyn compatible:

  • a generic method, like scaled<T> above;
  • a method that returns Self, such as fn doubled(&self) -> Self. Through a dyn, the caller doesn’t know what type Self is, so it can’t know how much space to make for the result;
  • a function with no self, such as fn new() -> Self. There’s no value, so there’s no vtable pointer to look it up through;
  • a supertrait that needs Self: Sized, such as trait Shape: Clone. Worked example 2 meets this one.

The escape: where Self: Sized

Often only one or two methods cause the trouble, and you don’t need them on a dyn. Add where Self: Sized to those methods. Sized means “the size is known at compile time”, which is true of Circle but not of dyn Shape. The compiler leaves those methods out of the vtable, and the rest of the trait works with dyn:

trait Shape {
    fn area(&self) -> f64;
    fn doubled(&self) -> Self
    where
        Self: Sized;
}

#[derive(Debug)]
struct Circle {
    radius: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        self.radius * self.radius * 3.0
    }
    fn doubled(&self) -> Self {
        Circle {
            radius: self.radius * 2.0,
        }
    }
}

fn main() {
    let c = Circle { radius: 1.0 };
    let big = c.doubled();
    println!("{big:?}");

    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(c), Box::new(big)];
    for shape in &shapes {
        println!("area {}", shape.area());
    }
}

It prints:

Circle { radius: 2.0 }
area 3
area 12

doubled still works on a Circle. On a dyn Shape it doesn’t exist. Calling shapes[0].doubled() is a compile error that says “the doubled method cannot be invoked on a trait object”.

Box<dyn Error>, revisited

Part 12 used Box<dyn Error> and asked you to read it as “any error”. Now you can read it exactly: a box holding some type that implements std::error::Error, with a vtable for its methods, including Display. That’s why {e} prints the right message for every kind of error.

? can turn a ParseIntError into a Box<dyn Error> because the standard library has an impl From<E> for Box<dyn Error> for every error type E. Strings convert too, through .into(). Sometimes you need the original type back. downcast_ref asks “is the value in this box really a ParseIntError?” and gives you an Option:

use std::error::Error;
use std::num::ParseIntError;

fn parse_age(text: &str) -> Result<u8, Box<dyn Error>> {
    let age: u8 = text.trim().parse()?;
    if age > 150 {
        return Err(format!("{age} is too old").into());
    }
    Ok(age)
}

fn main() {
    for input in ["42", "abc", "200"] {
        match parse_age(input) {
            Ok(age) => println!("{input}: age {age}"),
            Err(e) => {
                let kind = if e.downcast_ref::<ParseIntError>().is_some() {
                    "a ParseIntError"
                } else {
                    "another error"
                };
                println!("{input}: {e} ({kind})");
            }
        }
    }
}

It prints:

42: age 42
abc: invalid digit found in string (a ParseIntError)
200: 200 is too old (another error)

The two errors have different concrete types inside the box. {e} reached each one’s Display through the vtable, and downcast_ref checked which type was really there.

Any: the most general trait object

std::any::Any is a trait that every type implements, as long as it doesn’t hold a borrow. A &dyn Any can be “anything”, and downcast_ref asks whether it’s a particular type:

use std::any::Any;

fn describe(value: &dyn Any) {
    if let Some(n) = value.downcast_ref::<i32>() {
        println!("an i32: {n}");
    } else if let Some(s) = value.downcast_ref::<String>() {
        println!("a String: {s}");
    } else {
        println!("something else");
    }
}

fn main() {
    describe(&42);
    describe(&String::from("hello"));
    describe(&1.5);
}

It prints:

an i32: 42
a String: hello
something else

Each type gets a unique ID while compiling, and Any‘s vtable has a method that returns it. downcast_ref::<i32> compares that ID with the ID of i32. It’s a real tool, but use it rarely. A chain of “is it this type? is it that type?” is usually a sign that an enum or a trait method would be clearer.

Worked example: a list of password rules

Here’s a realistic use. A sign-up form checks a password against a list of rules. Each rule is its own type with its own data, and the list is built at run time, so we can add or drop rules without touching the checking code:

trait Rule {
    fn check(&self, password: &str) -> Result<(), String>;
}

struct MinLength(usize);

struct HasDigit;

struct NotCommon {
    banned: Vec<String>,
}

impl Rule for MinLength {
    fn check(&self, password: &str) -> Result<(), String> {
        if password.chars().count() >= self.0 {
            Ok(())
        } else {
            Err(format!("needs at least {} characters", self.0))
        }
    }
}

impl Rule for HasDigit {
    fn check(&self, password: &str) -> Result<(), String> {
        if password.chars().any(|c| c.is_ascii_digit()) {
            Ok(())
        } else {
            Err(String::from("needs a digit"))
        }
    }
}

impl Rule for NotCommon {
    fn check(&self, password: &str) -> Result<(), String> {
        if self.banned.iter().any(|b| b == password) {
            Err(String::from("is too common"))
        } else {
            Ok(())
        }
    }
}

fn problems(rules: &[Box<dyn Rule>], password: &str) -> Vec<String> {
    rules
        .iter()
        .filter_map(|rule| rule.check(password).err())
        .collect()
}

fn main() {
    let rules: Vec<Box<dyn Rule>> = vec![
        Box::new(MinLength(8)),
        Box::new(HasDigit),
        Box::new(NotCommon {
            banned: vec![String::from("password1"), String::from("12345678")],
        }),
    ];

    for password in ["cat", "password1", "blue-horse-7"] {
        let found = problems(&rules, password);
        if found.is_empty() {
            println!("{password}: ok");
        } else {
            println!("{password}: {}", found.join(", "));
        }
    }
}

It prints:

cat: needs at least 8 characters, needs a digit
password1: is too common
blue-horse-7: ok

The three rule types have different sizes. HasDigit holds nothing, MinLength holds a number and NotCommon holds a Vec. They still sit in one list, because the list holds boxes, and every Box<dyn Rule> is the same 16 bytes on a 64-bit machine. problems is compiled once and works for any rule anyone writes later.

A list of closures works the same way. Vec<Box<dyn Fn(&str) -> bool>> holds closures of different types (each closure has its own type, from Part 16) behind one trait, Fn.

Worked example: cloning a list of shapes

You want to copy a Vec<Box<dyn Shape>>. Vec has clone, so you ask that every shape be cloneable, by making Clone a supertrait:

trait Shape: Clone {
    fn area(&self) -> f64;
}

#[derive(Clone)]
struct Circle {
    radius: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        self.radius * self.radius * 3.0
    }
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle { radius: 1.0 })];
    let copy = shapes.clone();
    println!("{}", copy.len());
}

It prints:

error[E0038]: the trait `Shape` is not dyn compatible
...
1 | trait Shape: Clone {
  |       -----  ^^^^^ ...because it requires `Self: Sized`
  |       |
  |       this trait is not dyn compatible...

Read it from the caret. Clone requires Self: Sized, because clone returns Self. That’s the “method that returns Self” rule again, arriving through a supertrait. A Shape that needs Clone can never be dyn.

The fix is a method that returns a box instead of Self. A Box<dyn Shape> has a known size, so this method fits in a vtable. Then we implement Clone for Box<dyn Shape> ourselves. The orphan rule from Part 14 allows it, because Shape is our own trait:

trait Shape {
    fn area(&self) -> f64;
    fn box_clone(&self) -> Box<dyn Shape>;
}

#[derive(Clone)]
struct Circle {
    radius: f64,
}

#[derive(Clone)]
struct Square {
    side: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        self.radius * self.radius * 3.0
    }
    fn box_clone(&self) -> Box<dyn Shape> {
        Box::new(self.clone())
    }
}

impl Shape for Square {
    fn area(&self) -> f64 {
        self.side * self.side
    }
    fn box_clone(&self) -> Box<dyn Shape> {
        Box::new(self.clone())
    }
}

impl Clone for Box<dyn Shape> {
    fn clone(&self) -> Self {
        self.box_clone()
    }
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle { radius: 1.0 }),
        Box::new(Square { side: 2.0 }),
    ];
    let copy = shapes.clone();
    let total: f64 = copy.iter().map(|s| s.area()).sum();
    println!("{} shapes copied, total area {total}", copy.len());
}

It prints:

2 shapes copied, total area 7

Each type’s box_clone knows its own concrete type, so it can call the derived clone and box the result. The vtable picks the right box_clone for each item, exactly like area.

Tips and traps

  • E0308 when you build a Vec of boxes. vec![Box::new(Circle { .. }), Box::new(Square { .. })] with no type gives “expected Circle, found Square“. The compiler doesn’t guess that you want dyn. Write the type: let shapes: Vec<Box<dyn Shape>> = ....
  • E0782, “expected a type, found a trait”. You wrote Box<Shape>. Since edition 2021 a trait used as a type needs dyn: Box<dyn Shape>. The help: line shows where.
  • E0277, “the size … cannot be known at compilation time”. You used dyn Shape by value, as a parameter or a variable. Put it behind a pointer: &dyn Shape or Box<dyn Shape>. Or make the function generic with impl Shape.
  • E0038, “the trait is not dyn compatible”. The note under it names the method. Add where Self: Sized to that method if you don’t need it on a dyn, or move it to another trait.
  • dyn everywhere, by habit from other languages. In Java or C#, interface calls are dynamic. In Rust, generics are the default and cost nothing at run time. Reach for dyn when you need a mixed collection or a type chosen at run time.
  • Downcasting in a long if let chain. If you keep asking “is it a Circle?”, the type list is probably fixed. An enum with a match is clearer, and the compiler checks you covered every case.

A trait object is two pointers: one to the value, and one to a table that says how to use it.

Exercises

Exercise 1. On a 64-bit machine, how many bytes is each of these? Decide first, then run a program that prints size_of for each: &[u8], &dyn Display, &Box<dyn Display> and Vec<Box<dyn Display>>. (Display is the standard trait from Part 14, so you don’t need to write one.)

Exercise 2. This trait can’t be used with dyn. Without removing grown, change one line of the trait so that the program compiles, and keep the call small.grown(1.0) working.

trait Shape {
    fn area(&self) -> f64;
    fn grown(&self, by: f64) -> Self;
}

struct Square {
    side: f64,
}

impl Shape for Square {
    fn area(&self) -> f64 {
        self.side * self.side
    }
    fn grown(&self, by: f64) -> Self {
        Square {
            side: self.side + by,
        }
    }
}

fn main() {
    let small = Square { side: 1.0 };
    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(small.grown(1.0)), Box::new(small)];
    for shape in &shapes {
        println!("{}", shape.area());
    }
}

It prints:

error[E0038]: the trait `Shape` is not dyn compatible

Exercise 3. Write fn largest(shapes: &[Box<dyn Shape>]) -> Option<&dyn Shape>, which returns the shape with the biggest area, or None for an empty slice. Use it on a circle of radius 1, a square of side 2 and a circle of radius 0.5, and print the name and area of the winner. Hint: loop with a best variable, or use max_by with f64::total_cmp.

Answers

1. 16, 16, 8 and 24:

use std::fmt::Display;
use std::mem::size_of;

fn main() {
    println!("&[u8]:                 {}", size_of::<&[u8]>());
    println!("&dyn Display:          {}", size_of::<&dyn Display>());
    println!("&Box<dyn Display>:     {}", size_of::<&Box<dyn Display>>());
    let vec_size = size_of::<Vec<Box<dyn Display>>>();
    println!("Vec<Box<dyn Display>>: {vec_size}");
}

It prints:

&[u8]:                 16
&dyn Display:          16
&Box<dyn Display>:     8
Vec<Box<dyn Display>>: 24

A slice reference carries a length, and a dyn reference carries a vtable pointer, so both are fat. &Box<dyn Display> is a reference to a box, and the box itself has a known size, so the reference is an ordinary 8-byte pointer. The vtable pointer lives inside the box it points at. A Vec is always pointer, length and capacity, 24 bytes, whatever it holds.

2. grown returns Self, so it can’t go in a vtable. Add where Self: Sized to it in the trait. The impl doesn’t change, and small.grown(1.0) still works, because small is a Square, whose size is known:

trait Shape {
    fn area(&self) -> f64;
    fn grown(&self, by: f64) -> Self
    where
        Self: Sized;
}

struct Square {
    side: f64,
}

impl Shape for Square {
    fn area(&self) -> f64 {
        self.side * self.side
    }
    fn grown(&self, by: f64) -> Self {
        Square {
            side: self.side + by,
        }
    }
}

fn main() {
    let small = Square { side: 1.0 };
    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(small.grown(1.0)), Box::new(small)];
    for shape in &shapes {
        println!("{}", shape.area());
    }
}

It prints:

4
1

3. max_by compares two items at a time. Areas are f64, which has no Ord (because of NaN), so total_cmp gives the comparison. as_ref turns each &Box<dyn Shape> into a &dyn Shape:

use std::f64::consts::PI;

trait Shape {
    fn name(&self) -> &str;
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

struct Square {
    side: f64,
}

impl Shape for Circle {
    fn name(&self) -> &str {
        "circle"
    }
    fn area(&self) -> f64 {
        PI * self.radius * self.radius
    }
}

impl Shape for Square {
    fn name(&self) -> &str {
        "square"
    }
    fn area(&self) -> f64 {
        self.side * self.side
    }
}

fn largest(shapes: &[Box<dyn Shape>]) -> Option<&dyn Shape> {
    shapes
        .iter()
        .map(|s| s.as_ref())
        .max_by(|a, b| a.area().total_cmp(&b.area()))
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle { radius: 1.0 }),
        Box::new(Square { side: 2.0 }),
        Box::new(Circle { radius: 0.5 }),
    ];
    match largest(&shapes) {
        Some(s) => println!("largest: {} with area {:.2}", s.name(), s.area()),
        None => println!("no shapes"),
    }
    let empty: Vec<Box<dyn Shape>> = Vec::new();
    println!("empty list gives None: {}", largest(&empty).is_none());
}

It prints:

largest: square with area 4.00
empty list gives None: true

What’s next

Trait objects showed one more thing a trait can carry: facts about a type that are looked up at run time. In Part 22, we’ll look at the rest of what traits can do: associated types, operator overloading with Add, Deref and Drop, and writing an iterator of our own.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.