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.
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Square(2.0))];
Try it
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.
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
&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 returnSelf, and the trait must not requireSized. Methods withwhere Self: Sizedare 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
dynis required. Bare trait object types withoutdynare a hard error in edition 2021 and later. - Upcasting
&dyn Subto&dyn Superis supported since Rust 1.86. Before that you needed anas_supermethod. - Downcasting needs
Any, as in the second example;dyn Anycan only downcast to'statictypes. - Generics or dyn? Use generics (
impl Trait,T: Trait) for speed and fixed types; usedynfor heterogeneous collections and runtime choice. Cloneis not dyn-compatible because it returnsSelf; use aclone_boxmethod when needed.
Related
trait,impl,where,move- Lessons: Trait objects, Traits in depth, Closures