I am learning Dyn Traits in Rust. I see two options to use it
- &Box
- &dyn TraitName
When should I use the first and when should I use the second?
I don't see significant difference in my code (process_animal
and process_animal_box
functions)
My code
struct Cat {}
struct Dog {}
trait Animal {
fn say(&self);
}
impl Animal for Cat {
fn say(&self) {
println!("Meow!!!");
}
}
impl Animal for Dog {
fn say(&self) {
println!("Woow!");
}
}
fn process_animal(animal: &dyn Animal) {
animal.say();
}
fn process_animal_box(animal: &Box<dyn Animal>) {
animal.as_ref().say();
}
fn main() {
let cat = Cat {};
process_animal(&cat);
let dog: Box<dyn Animal> = Box::new(Dog {});
process_animal_box(&dog);
}