Let me show my problem with the standard Animal
example:
pub trait Animal {
fn age(&self, system: &Coordinates) -> i32;
}
pub struct Cat{ pub age: i32 }
impl Animal for Cat {
fn age(&self, system: &Coordinates) -> i32 { self.age }
}
pub struct Zoo {
pub zoo: Vec<Box<dyn Animal>>
}
impl Zoo {
pub fn add_animal(&self, a: &dyn Animal) {
self.zoo.push(Box::new(a));
}
}
Compiler complaints about:
The trait `Animal` is not implemented for `&dyn Animal
I've learned in the docs that &dyn Animal
and Animal
are different types. But I don't know how to make it working. Can I implement:
impl Animal for &dyn Animal {}
and make just delegations ? This doesn't sound right to me ... Or do I have to implement &dyn Animal
for Cat
and all other animals I'll have in my code? The last option would be just silly copy&paste of the very same code.
So I've tried to impl Animal for &dyn Animal {}
and now compiler complains this data with an anonymous lifetime `'_`
for add_animal()
.
I'm sure this is a very basic problem, so what is the rust-onic way to create such a structure?