RRust By Example
advancedTraits

Trait Objects (dyn Trait)

Use trait objects for dynamic dispatch with dyn keyword.

Trait Objects (dyn Trait)

Use trait objects for dynamic dispatch with dyn keyword.

Difficulty

Advanced

Code

rust
trait Animal {
    fn speak(&self) -> &str;
}

struct Dog;
struct Cat;

impl Animal for Dog {
    fn speak(&self) -> &str { "Woof!" }
}

impl Animal for Cat {
    fn speak(&self) -> &str { "Meow!" }
}

fn make_animal(kind: &str) -> Box<dyn Animal> {
    match kind {
        "dog" => Box::new(Dog),
        _ => Box::new(Cat),
    }
}

fn main() {
    let animals: Vec<Box<dyn Animal>> = vec![
        make_animal("dog"),
        make_animal("cat"),
    ];
    for a in &animals {
        println!("{}", a.speak());
    }
}

Explanation

dyn Trait enables dynamic dispatch across different types.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the traits category to build a complete understanding of this topic.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Traits Examples