0

I am learning Dyn Traits in Rust. I see two options to use it

  1. &Box
  2. &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);
}
mascai
  • 1,373
  • 1
  • 9
  • 30

1 Answers1

1

Box<T> can be reborrowed into &T, so you pretty much never need to take &Box<T> as argument, simillarly to guidelines around &str and &String

Take Box<T> (note absence of &) whenever you need ownership.

Ivan C
  • 1,772
  • 1
  • 8
  • 13