skip to content

Vtables and Dynamic Dispatch

dyn Trait erases the concrete type behind a pointer and a vtable, trading inlining for one compiled copy. Interviewers ask when to choose it and what makes a trait dyn-incompatible.

on this pageshow

questions

5

In a Rust drawing app, why must a canvas holding circles and rectangles together be a `Vec<Box<dyn Shape>>` rather than a `Vec<T>` with `T: Shape`?

level: juniorimportance: must knowfreq 76%

answer

  1. a Vec holds one element type
  2. T is fixed per instantiation
  3. erase the concrete type
  4. unsized, so behind a pointer

basics

~20 s

A Vec has one element type and a generic T: Shape is one concrete type, so circles and rectangles cannot share a Vec<T>. Box<dyn Shape> erases each concrete type behind a pointer and a vtable, giving every element one type.

solid answer

~40 s

A `Vec<T>` holds elements of exactly one type, and a bound like `T: Shape` does not change that: the compiler picks one concrete `T` per use, so `vec![Circle { .. }, Square { .. }]` fails with E0308 "mismatched types". `dyn Shape` is a **trait object**: a type meaning "some value that implements `Shape`", with the concrete type erased. It is unsized, because a circle and a labelled rectangle differ in size, so it has to live behind a pointer such as `Box<dyn Shape>`, `&dyn Shape` or `Rc<dyn Shape>`. Every `Box<dyn Shape>` has the same type and size, so they fit in one `Vec`, and `s.area()` is dispatched at run time to the right implementation. When the set of shapes is closed and known, an enum is the other honest answer.

code

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

struct Circle { r: f64 }
struct Rect { w: f64, h: f64, label: String }

impl Shape for Circle {
    fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r }
    fn name(&self) -> &str { "circle" }
}
impl Shape for Rect {
    fn area(&self) -> f64 { self.w * self.h }
    fn name(&self) -> &str { &self.label }
}

fn main() {
    let canvas: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle { r: 1.0 }),
        Box::new(Rect { w: 2.0, h: 3.0, label: "door".to_string() }),
    ];
    for s in &canvas {
        println!("{} {:.2}", s.name(), s.area());
    }
}

go deeper

for a junior

Recall that a Vec holds one element type, that dyn Shape erases the concrete type, and that it must sit behind Box, & or Rc. Show the annotated Vec<Box<dyn Shape>>.

for a middle

Explain why dyn Shape is unsized, that Box<Circle> becomes Box<dyn Shape> by an unsized coercion, and that each call goes through the vtable at run time.

for a senior

Weigh Box<dyn Shape> against an enum: open versus closed sets, a heap allocation per element, indirect calls, and which choice makes adding a shape a compile error.

for a principal

Frame the canvas as an extension point: a trait object lets other crates add shapes, an enum keeps the set auditable. Say which one the rendering hot path can afford.

## The problem: one Vec, several concrete types A drawing app keeps everything on the canvas in one list and redraws it each frame. The shapes are different structs, `Circle { r }` and `Rect { w, h, label }`, and both implement a `Shape` trait with `area` and `name`. The natural first attempt is a generic: `Vec<T>` where `T: Shape`. It does not compile once two kinds of shape go in. - A `Vec<T>` stores elements of **one** type, laid out side by side. Every slot is `size_of::<T>()` bytes. - A generic parameter `T` is filled in with **one concrete type** at each use. `T: Shape` restricts which type that can be; it does not mean "any mixture of `Shape` types". - So `vec![Circle { r: 1.0 }, Square { s: 2.0 }]` fails with **E0308** "mismatched types", "expected `Circle`, found `Square`". Writing `vec![Box::new(Circle { .. }), Box::new(Rect { .. })]` without a type annotation fails the same way, because the first element fixes the type as `Box<Circle>`. ## The answer: a trait object `dyn Shape` is a **trait object type**. It stands for "a value of some type that implements `Shape`", and it deliberately forgets which type. Two consequences follow. 1. **It is dynamically sized.** On a 64-bit target a circle is 8 bytes and a rectangle with a `String` label is 40, so `dyn Shape` has no size the compiler can know. You cannot have a local of type `dyn Shape`: `let s: dyn Shape = Circle { .. };` is rejected with E0308 and E0277 ("the size for values of type `dyn Shape` cannot be known at compilation time"). 2. **It lives behind a pointer.** `Box<dyn Shape>` (owned, on the heap), `&dyn Shape` (borrowed) and `Rc<dyn Shape>` or `Arc<dyn Shape>` (shared ownership) are all fixed-size values. Each one carries the data pointer plus a pointer to a **vtable**, a table of function pointers for that concrete type's `Shape` implementation. Because every element is now the same type, `Box<dyn Shape>`, the `Vec` is happy. Putting a `Box<Circle>` into it is an **unsized coercion**: the compiler converts `Box<Circle>` to `Box<dyn Shape>` wherever the expected type says so, which is why the annotation `let canvas: Vec<Box<dyn Shape>>` matters. ## What a call does `s.area()` on a `Box<dyn Shape>` is **dynamic dispatch**: at run time the program loads the `area` entry from that element's vtable and calls it. A circle runs `Circle::area`, a rectangle runs `Rect::area`, and the loop never knows which is which. The generic version, by contrast, would be **statically dispatched**: one copy of the function per concrete type, resolved at compile time. ## Choosing the pointer and the alternative | Need | Write | |---|---| | The canvas owns its shapes | `Vec<Box<dyn Shape>>` | | Shapes are owned elsewhere and only borrowed | `Vec<&dyn Shape>` | | Several owners share one shape | `Vec<Rc<dyn Shape>>` | | The set of shapes is fixed and known | an `enum Shape { Circle(..), Rect(..) }` | The enum deserves its row. When you control every variant, an enum stores the shapes inline without a heap allocation per element, and adding a variant makes every `match` without a wildcard arm a compile error until it handles the new shape. A trait object wins when the set is **open**: other modules, crates or plugins add shapes without touching the canvas code. ## Syntax points that trip people up - The `dyn` keyword is required. Since the 2021 edition a bare trait name in type position, `Box<Shape>`, is a hard error, **E0782** "expected a type, found a trait"; older editions only warned. - A trait object is written with one ordinary trait plus optional auto traits and a lifetime: `Box<dyn Shape + Send>` is what a canvas handed to another thread needs. - Not every trait can be made into a trait object. A trait whose methods are generic or return `Self` fails with E0038, a rule with its own question. - How long a borrowed trait object may live, the `+ 'a` part, is covered with higher-ranked bounds and trait-object lifetimes. ## Summary `Vec<T: Shape>` means "a vector of one shape type"; `Vec<Box<dyn Shape>>` means "a vector of pointers to any shapes". The second erases each concrete type behind a pointer and a vtable, pays for it with a heap allocation per element and an indirect call per method, and in return lets one list hold every kind of shape, including kinds written after the canvas was compiled.

  • When would you use an enum instead of `Vec<Box<dyn Shape>>`?
    When you own the complete, closed set of shapes. An enum stores each shape inline with no per-element heap allocation, dispatch is a `match` the compiler can see through, and adding a variant breaks every `match` without a wildcard arm at compile time. Choose `Box<dyn Shape>` when the set is open: other crates or plugins must add shapes without editing the canvas.
  • Can the canvas be `Vec<&dyn Shape>` instead of boxes?
    Yes, if something else owns the shapes and outlives the vector. `&dyn Shape` is the same two-word pointer without the heap allocation or ownership, so the borrow checker ties the vector's use to the owners' scope. It suits a temporary list built for one redraw; a canvas that owns its contents needs `Box<dyn Shape>`.

  • Says T: Shape lets one Vec<T> hold any mix of types implementing Shape.
  • Writes Box<Shape> without dyn and expects it to compile on the 2021 or 2024 edition.
  • Tries to store dyn Shape directly in a Vec or a local without a pointer.
  • Thinks dyn Shape is a pointer type itself rather than an unsized type behind one.
  • Never mentions an enum as the alternative when every shape type is known.
open as a page

In Rust, what does a `&dyn Shape` hold at run time, and what does a method call through it cost versus a generic call?

level: middleimportance: must knowfreq 62%

basics

~20 s

A pointer to dyn Shape is a fat pointer: a data pointer plus a vtable pointer, the vtable holding size, alignment, drop glue and method pointers. Each call is indirect through it and generally not inlined; generics compile a direct call per type.

open as a page

A Rust `Plugin` trait with a generic `configure<T>` method and a `duplicate(&self) -> Self` method fails with E0038 at `Box<dyn Plugin>`: why, and how do you fix it?

level: seniorimportance: should knowfreq 52%

basics

~20 s

A vtable needs one function pointer per method: a generic method has unboundedly many instantiations and a Self return has no size behind dyn, so Plugin is not dyn compatible. Adding where Self: Sized to those two methods removes them from the vtable.

open as a page

In Rust 1.86 and later, how do you get a concrete `Metrics` plugin back out of a `Box<dyn Plugin>`, and what did code need before trait-object upcasting?

level: seniorimportance: should knowfreq 34%

basics

~20 s

Declare trait Plugin: Any, upcast the &dyn Plugin to &dyn Any (allowed since Rust 1.86) and call downcast_ref::<Metrics>(), or upcast the Box to Box<dyn Any> and call downcast. Before 1.86 each plugin implemented an as_any(&self) -> &dyn Any method.

open as a page

Your team plans third-party Rust plugins as dynamic libraries whose entry point returns `Box<dyn Plugin>`: what does that boundary require, and what would you choose instead?

level: principalimportance: nice to knowfreq 22%

basics

~20 s

Rust promises no stable layout for repr(Rust) types or trait-object vtables, so a Box<dyn Plugin> crossing a separately built library needs, at minimum, the same compiler and trait crate on both sides. A C-ABI function table, WebAssembly or a process are sturdier.

open as a page