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
This example demonstrates how to use trait objects (dyn trait) in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the traits category to build a complete understanding of this topic.