手动删除引用包装器的 Rust 生命周期问题

Rust lifetime issue with manually dropped reference wrapper

我正在尝试用包含可变引用的自定义删除逻辑在 Rust 中编写 class,但无论我做什么,我都无法计算出生命周期,并且编译器错误消息没有帮助。谁能告诉我做错了什么,以及如何解决?

注意:我已经尝试了我能想到的对这段代码的所有修改,例如删除或反转 'b: 'a 约束,但无论我做什么,编译器都会产生一种难以理解的生命周期错误消息或其他消息。

pub struct MapRef<'a, K: Eq + Hash, V>{
    p: &'a mut HashMap<K, V>,
}
impl<'a, K: Eq + Hash, V> MapRef<'a, K, V> {
    pub fn new(p: &'a mut HashMap<K, V>) -> Self {Self{p}}
}
impl<'a, K: Eq + Hash, V> MapRef<'a, K, V> {
    pub fn reborrow<'b: 'a>(&'b mut self) -> MapRef<'b, K, V> {
        Self::new(self.p)
    }
}
impl<'a, K: Eq + Hash, V> Drop for MapRef<'a, K, V> {
    fn drop(&mut self) {
        println!("dropping ref");
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() -> Result<(), String> {
        let mut m: HashMap<(), ()> = HashMap::new();
        let mut r1 = MapRef::new(&mut m);

        {
            let r2 = r1.reborrow();
        }

        Ok(())
    }
}

示例错误消息:

   |
37 |             let r2 = r1.reborrow();
   |                      ^^ borrowed value does not live long enough
...
41 |     }
   |     -
   |     |
   |     `r1` dropped here while still borrowed
   |     borrow might be used here, when `r1` is dropped and runs the `Drop` code for type `util::MapRef`

事实证明,编译器建议添加错误的 'b: 'a 约束的原因是因为 Self::new 中的 Self 隐式引用了 'a 生命周期。解决方案是将 Self::new 更改为 MapRef::new,这允许您删除不良约束。

impl<'a, K: Eq + Hash, V> MapRef<'a, K, V> {
    pub fn reborrow<'b>(&'b mut self) -> MapRef<'b, K, V> {
        MapRef::new(self.p)
    }
}

请注意,现在可以省略 'b,但为了清楚起见,我将其留在此处。