liveBook · Manning

Dyn

As explained in Idiomatic Rust

The dyn keyword marks a Rust type position as containing a dynamically dispatched trait object.

The `dyn` keyword marks a trait object, letting different concrete types be used through a shared trait interface. Rust uses a compiler-generated vtable for runtime dynamic dispatch. Trait objects are unsized, so store them behind a pointer such as `Box`; a `Vec` cannot hold `dyn MyTrait` directly. section 2.2.6 section 2.2.6

let mut v = Vec::<Box<dyn MyTrait>>::new();

v.push(Box::new(MyStruct1 {}));          #1
v.push(Box::new(MyStruct2 {}));            #2

v.iter().for_each(|i| i.trait_hello());                   #3
// v.iter().for_each(|i| i.struct_hello()); error!    #4

This vector stores two concrete types behind `Box<dyn MyTrait>` and calls their shared trait method. The concrete structs’ methods are not directly available through the trait object. section 2.2.6

How Idiomatic Rust covers it

How deep it goes
Explains vtable dispatch and unsized storage, then demonstrates boxed trait objects; broader tradeoffs are deferred.
Examples
Demonstrates MyStruct1 and MyStruct2 in a vector of boxed trait objects, invoking their shared method.
What you can do after
Apply `dyn` with `Box` to store differing trait implementations together and call their shared interface.
How it connects
Connects trait objects with dynamic dispatch, vtables, Sized, smart pointers, Vec, and downcasting through Any.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.