首页 > 解决方案 > 如何在指向同一结构中的数据的结构中存储可变引用?

问题描述

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());
            }
        }        
    }
}

我想要的是self.current_chunk_info与 got mut 值具有相同的生命周期HashMap,但我得到了以下错误:

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

怎么修?

标签: structrusthashmaplifetime

解决方案


推荐阅读