FerrousPath

Level 3 · Systems· Lesson 3 of 11 · 25 min

Trait objects and dynamic dispatch

dyn Trait, vtables and fat pointers, dyn compatibility, and choosing between static and dynamic dispatch.

The limit of generics

A Vec<T> holds one type. A function generic over T: Shape is compiled for one T at a time. When the concrete type is known only at runtime — plugins, GUI widgets, a list of mixed shapes — you need dynamic dispatch.

trait Shape {
    fn area(&self) -> f64;
    fn name(&self) -> String {
        "shape".to_string()
    }
}

struct Circle(f64);
struct Rect(f64, f64);

impl Shape for Circle {
    fn area(&self) -> f64 { std::f64::consts::PI * self.0 * self.0 }
    fn name(&self) -> String { "circle".into() }
}

impl Shape for Rect {
    fn area(&self) -> f64 { self.0 * self.1 }
}

fn largest(shapes: &[Box<dyn Shape>]) -> &dyn Shape {
    shapes
        .iter()
        .max_by(|a, b| a.area().total_cmp(&b.area()))
        .expect("non-empty")
        .as_ref()
}

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

dyn Shape is a trait object: “some type implementing Shape, to be determined at runtime”. Its size is unknown at compile time, so it always lives behind a pointer — &dyn Shape, Box<dyn Shape>, Arc<dyn Shape>.

How it works: fat pointers and vtables

A pointer to a trait object is two words:

Box<dyn Shape>
┌────────────┐      ┌──────────────┐
│ data ptr   │ ───▶ │ Circle(1.0)  │
├────────────┤      └──────────────┘
│ vtable ptr │ ───▶ ┌──────────────────────┐
└────────────┘      │ drop_in_place        │
                    │ size, align          │
                    │ <Circle as Shape>::area │
                    │ <Circle as Shape>::name │
                    └──────────────────────┘

Calling s.area() loads the function pointer from the vtable and makes an indirect call. One vtable exists per (concrete type, trait) pair. The cost is one pointer load and — more importantly — the loss of inlining.

use std::mem::size_of;

trait T { fn f(&self); }

fn main() {
    println!("&u8          : {}", size_of::<&u8>());
    println!("&[u8]        : {}", size_of::<&[u8]>());      // pointer + length
    println!("&dyn T       : {}", size_of::<&dyn T>());     // pointer + vtable
    println!("Box<dyn T>   : {}", size_of::<Box<dyn T>>());
}

Dyn compatibility

Not every trait can be made into an object. A trait is dyn-compatible (formerly “object safe”) only if every method can be called through a vtable without knowing the concrete type. The main rules:

  • Methods must not be generic over types (a vtable cannot hold infinitely many instantiations).
  • Methods must not return Self or take Self by value in arguments.
  • The trait must not require Self: Sized.
  • No associated constants; associated functions without a receiver need an opt-out.

Opt a method out with where Self: Sized; it then exists on concrete types but not on dyn Trait:

trait Animal {
    fn name(&self) -> String;

    fn duplicate(&self) -> Self
    where
        Self: Sized; // excluded from the vtable
}

#[derive(Clone)]
struct Cat;

impl Animal for Cat {
    fn name(&self) -> String { "cat".into() }
    fn duplicate(&self) -> Self { self.clone() }
}

fn main() {
    let a: Box<dyn Animal> = Box::new(Cat);
    println!("{}", a.name());
    // a.duplicate(); // ❌ not available on dyn Animal
    let _c = Cat.duplicate();
}

This is why Clone is not dyn-compatible, and why Iterator is: its generic adapters all carry where Self: Sized.

Upcasting and Any

Since Rust 1.86 a trait object can be coerced to an object of its supertrait:

use std::any::Any;
use std::fmt::Debug;

trait Component: Debug + Any {
    fn update(&mut self);
}

#[derive(Debug)]
struct Health(u32);

impl Component for Health {
    fn update(&mut self) { self.0 = self.0.saturating_sub(1); }
}

fn main() {
    let mut c: Box<dyn Component> = Box::new(Health(10));
    c.update();

    let as_debug: &dyn Debug = &*c;            // upcast to a supertrait
    println!("{as_debug:?}");

    let as_any: &dyn Any = &*c;                // upcast to Any…
    if let Some(h) = as_any.downcast_ref::<Health>() { // …then downcast to the concrete type
        println!("health = {}", h.0);
    }
}

Downcasting is an escape hatch. If you find yourself doing it routinely, an enum probably models the problem better.

Static or dynamic?

Generics (impl Trait, T: Trait) Trait objects (dyn Trait)
Dispatch direct, inlinable indirect through vtable
Code size one copy per type one copy total
Compile time grows with instantiations lower
Mixed types in one collection no yes
Needs dyn compatibility no yes

And do not forget the third option: an enum. When the set of variants is closed and known to you, enum Shape { Circle(..), Rect(..) } with a match is faster than dyn, needs no allocation, and gets exhaustiveness checking. Use dyn when the set is open — when other crates must be able to add implementations.

Function pointers and closures follow the same split: impl Fn(i32) -> i32 is static; Box<dyn Fn(i32) -> i32> is dynamic and lets you store different closures in one Vec.

Exercises

  1. Build a tiny plugin system: trait Command { fn name(&self) -> &str; fn run(&mut self, args: &[&str]) -> String; } and a registry HashMap<String, Box<dyn Command>>.
  2. Rewrite the shapes example with an enum. Benchmark area summed over a million shapes for both designs.
  3. Make this trait dyn-compatible without removing methods: trait Visitor { fn visit<T: Debug>(&mut self, t: &T); fn done(self) -> String; }.
Hint for 3

Replace the generic parameter with &dyn Debug, and either add where Self: Sized to done or change its receiver to self: Box<Self>, which is callable on a Box<dyn Visitor>.

Check your understanding

Pick an answer to see the explanation.

  1. 1.How large is a &dyn Trait on a 64-bit target?

  2. 2.Which method prevents a trait from being used as dyn Trait unless it is given a where Self: Sized bound?

  3. 3.When is dyn Trait the better choice over generics?

Key terms in this lesson

Finished the lesson and the exercises?