There is a trait Animal
defined and 2 struct (Cat
, Dog
) that implement it:
use std::rc::Rc;
trait Animal {
fn make_sound(&self) -> String;
}
struct Cat;
impl Animal for Cat {
fn make_sound(&self) -> String {
"meow".to_string()
}
}
struct Dog;
impl Animal for Dog {
fn make_sound(&self) -> String {
"woof".to_string()
}
}
Then I define a struct Zoo
to accept Animal
into a Vec<Rc<dyn Animal>>
:
struct Zoo {
animals: Vec<Rc<dyn Animal>>,
}
impl Default for Zoo {
fn default() -> Self {
Self { animals: Vec::new() }
}
}
impl Zoo {
pub fn add(&mut self, animal: Rc<dyn Animal>) {
self.animals.push(animal);
}
pub fn add_many(&mut self, animals: Vec<Rc<dyn Animal>>) {
self.animals = animals;
}
}
fn main() {
let dog = Dog;
let cat = Cat;
let mut zoo = Zoo::default();
zoo.add(Rc::new(cat));
let mut vector = Vec::new();
vector.push(Rc::new(dog));
zoo.add_many(vector);
}
Now add(mut self, animal: Rc<dyn Animal>)
works as expected, but add_many(mut self, animals: Vec<Rc<dyn Animal>>)
complains about
expected trait object
dyn Animal
, found structDog
Why is Vec<Rc<Dog>>
not recognized as Vec<Rc<(dyn Animal)>>
?