pub trait Dinosaur {
fn roar(&mut self);
}
pub struct Astrodon<'a> {
data: &'a Vec<usize>,
}
impl<'a> Dinosaur for Astrodon<'a> {
fn roar(&mut self) {
println!("Astrodon: {:?}", self.data);
}
}
pub struct Zoo {
pub data: Vec<usize>,
pub dinosaur: Vec<Box<dyn Dinosaur>>,
}
fn main() {
// let data = vec![1,2,3,4,5,6];
// let mut v: Vec<Box<dyn Dinosaur>> = Vec::new();
// v.push(Box::new(Astrodon{data: &data}));
// for d in v.iter_mut()
// {
// d.roar();
// }
let mut z = Zoo {data: vec![1,2,3,4,5,6], dinosaur: Vec::new()};
z.dinosaur.push(Box::new(Astrodon{data: &z.data}));
for d in z.dinosaur.iter_mut() {
d.roar();
}
}
The code failed to compile due to lifetime issues. Why does it require a static lifetime? Any help will be appreciated!
But if you uncomment out the commented and comment out the rest, it works.
According to this(Forcing the order in which struct fields are dropped), Zoo.data will be dropped before dropping Zoo.dinosaur, so Zoo.dinosaur is pointing to invalid data when dropping, but even I moved Zoo.dinosaur in front of Zoo.data, it still did't work.