2
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.

  • There's a fundamental design problem to solve before looking at lifetimes here. You try to put the zoo in the dinosaurs ? The data structure doesn't seem logical. – Denys Séguret May 02 '21 at 06:52
  • 2
    You are creating a struct that references itslef https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct – lpiepiora May 02 '21 at 07:31
  • Summary of the duplicates: `Box` is the reason it requires `'static`, which is what the second linked question says. But even [if you fix that](https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=edc7ec7aac2ac5741ec0a6df57e6325f) you just get shunted into a twisty little maze of lifetime errors, all alike, for the reasons explained in the answers to the question lpiepiora linked. – trent May 02 '21 at 10:19

0 Answers0