Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Keywords and Statements

The dyn keyword

Reference for Rust dyn: trait objects behind Box, & and Rc, vtables and dynamic dispatch, dyn compatibility rules, Any downcasting and cost versus generics.

dyn Trait is the type of a trait object: a value whose concrete type is known only at run time. Because its size is not known at compile time, it always lives behind a pointer: &dyn Trait, Box<dyn Trait>, Rc<dyn Trait> and so on. These pointers are "fat": they hold the data pointer and a pointer to a vtable with the trait's methods.

Use trait objects when you need a collection of different types, plugin-style extension, or want to avoid generating a copy of code per type.

Rust
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Square(2.0))];

Try it

Rust A collection of different types

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.

Rust Dyn compatibility and downcasting

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.

Syntax

Rust
&dyn Trait
&mut dyn Trait
Box<dyn Trait>
Box<dyn Trait + Send + 'static>
Rc<dyn Trait>, Arc<dyn Trait + Send + Sync>
&dyn Fn(i32) -> i32
Part Description
dyn Trait An unsized type. One principal trait (plus auto traits) is allowed.
+ Send, + Sync Auto traits may be added to the object type.
+ 'a Lifetime bound of the hidden type. Box<dyn Trait> defaults to 'static; &'a dyn Trait defaults to 'a.

Usage notes

  • Dyn compatibility (formerly "object safety"): methods need a receiver (&self, &mut self, self: Box<Self>, ...), must not be generic over types, must not return Self, and the trait must not require Sized. Methods with where Self: Sized are exempt.
  • Dynamic dispatch cost: each call goes through the vtable and cannot be inlined, but compile time and code size shrink compared to generics.
  • Writing dyn is required. Bare trait object types without dyn are a hard error in edition 2021 and later.
  • Upcasting &dyn Sub to &dyn Super is supported since Rust 1.86. Before that you needed an as_super method.
  • Downcasting needs Any, as in the second example; dyn Any can only downcast to 'static types.
  • Generics or dyn? Use generics (impl Trait, T: Trait) for speed and fixed types; use dyn for heterogeneous collections and runtime choice.
  • Clone is not dyn-compatible because it returns Self; use a clone_box method when needed.