Trait Objects and dyn
Box<dyn Trait> stores values of different types behind one interface using dynamic dispatch.
Example
trait Speak { fn speak(&self) -> String; }
struct Dog; struct Cat;
impl Speak for Dog { fn speak(&self) -> String { "Woof".into() } }
impl Speak for Cat { fn speak(&self) -> String { "Meow".into() } }
fn main() {
let pets: Vec<Box<dyn Speak>> = vec![Box::new(Dog), Box::new(Cat)];
for p in &pets { println!("{}", p.speak()); }
}Result
Woof Meow
Exercise
Dynamic dispatch keyword.
Box< Speak>
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.