Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 132 ยท Structs, Enums and Traits Basics

Trait Objects and Dynamic Dispatch

Learn Rust trait objects - dyn Trait, Box<dyn Trait>, vtables, object safety, static vs dynamic dispatch, heterogeneous collections and downcasting with Any.

A generic function such as fn show<T: Speak>(x: &T) is compiled once per concrete type. That is fast, but it has a limit: inside one Vec<T> every element must be the same type. What if you want a list of shapes where some are circles and some are rectangles, and you want to add a new kind of shape later without changing the list code? You need the compiler to decide at runtime which method to call. That mechanism is called dynamic dispatch, and the value you use is a trait object.

This lesson explains dyn Trait, how to store trait objects in boxes and references, what a vtable is, which traits are allowed (object safety), when to prefer static dispatch, how to build collections of mixed types and how to get the concrete type back with Any. You should know Traits and Box and the Heap.

A heterogeneous collection

Write dyn Trait for "some value of unknown concrete type that implements Trait". Because the size of such a value is unknown at compile time, you can only use it behind a pointer: &dyn Trait, Box<dyn Trait>, Rc<dyn Trait>.

Rust A Vec of Box dyn Shape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Box<dyn Shape> is a smart pointer to heap data of some type implementing Shape. Each Box::new(Circle {..}) is coerced (silently converted) from Box<Circle> to Box<dyn Shape>. The Vec holds three equally sized pointers even though the shapes behind them differ in size. If a new kind of shape appears in another module or crate, nothing here needs to change.

Without the type annotation Vec<Box<dyn Shape>>, the compiler would infer Vec<Box<Circle>> from the first element and complain about the second. The annotation is what says "a list of trait objects".

References to trait objects

You do not need a Box when you merely borrow. A &dyn Trait parameter accepts a reference to any implementor and avoids allocation:

Rust &dyn Trait as a parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

How dynamic dispatch works: the vtable

A reference or box to a concrete type is one pointer (a "thin" pointer). A &dyn Trait is a fat pointer of two words:

  1. a pointer to the data, and
  2. a pointer to a vtable (virtual table) for the concrete type and this trait.

The vtable is generated by the compiler once per (type, trait) pair. It holds the destructor, the size and alignment of the type, and the address of each trait method. A call shape.area() loads the function address from the vtable and jumps to it. You can see the fat pointer in the sizes:

Rust Thin and fat pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Slices and &str are fat pointers too (pointer plus length); dyn is the same idea with a vtable instead of a length.

Static versus dynamic dispatch

Rust gives you both. Compare the same function written two ways:

Rust Generic (static) and dyn (dynamic) dispatch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Generics (T: Trait, impl Trait) Trait objects (dyn Trait)
Dispatch resolved at compile time resolved at runtime via vtable
Speed can be inlined, fastest one indirect call, no inlining
Code size one copy per type (can grow) one copy
Mixed types in a collection no yes
Types known at compile time required not required (plugins, runtime config)
Extra allocation none usually a Box per value

The indirect call costs a few nanoseconds at most; in most programs it is irrelevant. Reach for generics by default and for dyn when you need a mixed collection, when the concrete type is chosen at runtime, to cut compile time and binary size, or to hide a complicated type behind a simple interface.

Object safety

Not every trait can become dyn. A trait must be dyn compatible (older name: object safe), because the vtable has to contain every method with a fixed signature. The main rules:

  • Methods must not return Self (the caller would have to know the size).
  • Methods must not have generic type parameters (the vtable cannot hold infinitely many versions).
  • The trait must not require Self: Sized.
  • Associated constants are not allowed.
Rust A trait that is not dyn compatible (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports:

TEXT
error[E0038]: the trait `Duplicate` is not dyn compatible
  --> main.rs:14:28
   |
14 |     let items: Vec<Box<dyn Duplicate>> = vec![Box::new(Token(1))];
   |                            ^^^^^^^^^ `Duplicate` is not dyn compatible
   |
note: for a trait to be dyn compatible it needs to allow building a vtable
  --> main.rs:2:28
   |
 1 | trait Duplicate {
   |       --------- this trait is not dyn compatible...
 2 |     fn duplicate(&self) -> Self;
   |                            ^^^^ ...because method `duplicate` references the `Self` type in its return type

Two fixes. You can return Box<dyn Duplicate> instead of Self. Or you can keep the method but exclude it from the vtable with where Self: Sized, so the rest of the trait stays usable as dyn:

Rust Opting a method out with where Self: Sized

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Generic methods and the clone problem are discussed further in Advanced Trait Techniques. The common trap: Clone itself returns Self, so dyn Clone is impossible. If you need to clone boxed trait objects, add a fn box_clone(&self) -> Box<dyn Trait> method to your trait.

Trait objects with lifetimes and Send

Box<dyn Trait> by default means Box<dyn Trait + 'static>: the concrete type must own its data (contain no short-lived borrows). To store borrowing types, write Box<dyn Trait + 'a>. To send trait objects to another thread, require it: Box<dyn Trait + Send>. You will meet this often as Box<dyn Error + Send + Sync> (Custom Error Types).

Trait objects as behavior you can swap

A struct can hold a boxed strategy and change it while running, which is the classic strategy pattern:

Rust Swappable behavior with Box dyn

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Downcasting with Any

Sometimes you hold a Box<dyn Trait> and need the concrete type back. Plain trait objects forget it, but the std::any::Any trait keeps a type id. Add an as_any method to your trait, then call downcast_ref:

Rust Downcasting with Any

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

downcast_ref::<T>() returns Some(&T) only if the hidden type is exactly T. Needing this often is a design smell: it usually means an enum would be a better fit (you would match on variants and the compiler would check completeness). Reserve Any for plugin-like systems and heterogeneous storage such as entity-component stores.

Since Rust 1.86 you can also convert &dyn SubTrait into &dyn SuperTrait directly (trait upcasting) when SubTrait: SuperTrait. See Advanced Traits.

When to use and when to avoid

  • Use dyn for mixed collections, plugin-style extension points, runtime-selected strategies, callbacks (Box<dyn Fn(i32) -> i32>), and to keep generic code from spreading through your type signatures.
  • Avoid dyn in hot inner loops where the call can be inlined, for tiny closed sets (an enum is simpler and faster, with no allocation), and for traits that need Self-returning or generic methods.
  • Prefer &dyn Trait over Box<dyn Trait> in parameters; box only when the value must be owned.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must a dyn Trait value live behind a pointer such as Box or &?

    dyn Trait is an unsized type: different implementors have different sizes. Pointers have a fixed size, so Box<dyn T> and &dyn T work.
  2. 2. What does a &dyn Trait reference contain?

    It is a fat pointer (two words): data pointer plus vtable pointer. The vtable holds the method addresses, size, alignment and destructor.
  3. 3. Which method makes a trait not dyn compatible?

    Returning Self requires knowing the concrete size, so the trait cannot be made into an object (E0038). Adding where Self: Sized to that method excludes it from the vtable.
  4. 4. When is a generic bound (T: Trait) a better choice than dyn Trait?

    Generics give static dispatch: the compiler specializes and can inline. dyn is for mixed collections and runtime choices.
  5. 5. What does part.as_any().downcast_ref::<Health>() return when the value is a Label?

    downcast_ref returns Some(&T) only when the hidden concrete type is T, and None otherwise.

Summary

  • dyn Trait is a trait object: a value of unknown concrete type, used behind &, Box, Rc or Arc.
  • Dynamic dispatch goes through a vtable carried by a fat pointer (data pointer plus vtable pointer).
  • Generics (static dispatch) are faster and can be inlined; trait objects allow mixed collections, runtime choice and one copy of the code.
  • A trait must be dyn compatible: no Self returns, no generic methods (unless where Self: Sized), no associated constants.
  • Box<dyn Trait> means 'static; add + Send or a lifetime when needed.
  • Any plus downcast_ref recovers the concrete type, but an enum is often the better design.

Next: Display, From and Standard Conversion Traits