0
struct ChunkUnpacketizer<'a> {
    id_2_chunk_info: HashMap<u32, ChunkInfo>,
    current_chunk_info: &'a mut ChunkInfo,
}

impl<'a> ChunkUnpacketizer<'a> {
    fn read_basic_header(&mut self) {
        let id = 32 as u32;

        match self.id_2_chunk_info.get_mut(&id) {
            Some(chunk_info) => {
                self.current_chunk_info = chunk_info;
            }
            None => {
                self.id_2_chunk_info.insert(id, ChunkInfo::new());
            }
        }        
    }
}

What I want is that the self.current_chunk_info has the same lifetime with the got HashMap mut value, but I got the following errors:

cannot infer an appropriate lifetime for autoref due to conflicting requirements
first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 175:5...
...so that reference does not outlive borrowed content
but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 74:6...
...so that reference does not outlive borrowed content

How to fix?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
Harlan Chen
  • 321
  • 5
  • 20
  • 1
    This is called a self-referential struct, and it's a common problem which is a pain-in-the-ass to solve. You better avoid such self-referential design whatsoever – Alexey S. Larionov Nov 08 '20 at 11:34
  • Does this answer your question? [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct) – pretzelhammer Dec 24 '20 at 19:44

0 Answers0