非词汇生命周期解决方法失败

时间:2017-06-07 15:53:42

标签: rust lifetime borrow-checker

get()返回对矢量项的引用,必要时预先推送该值:

struct Container {
    vec: Vec<i32>,
}
impl Container {
    fn find(&mut self, v: i32) -> Option<&mut i32> {
        None // we don't care the implementation
    }

    fn get(&mut self, v: i32) -> &mut i32 {
        match self.find(v) {
            Some(x) => x,
            None => {
                self.vec.push(v);
                self.vec.last_mut().unwrap()
            }
        }
    }
}

fn main() {
    let mut container = Container { vec: Vec::new() };
    let x = container.get(42);
}

它无法编译,因为我们尝试推送值self时仍然借用self.vec.push(v)

error[E0499]: cannot borrow `self.vec` as mutable more than once at a time
  --> test.rs:13:17
   |
10 |         match self.find(v) {
   |               ---- first mutable borrow occurs here
...
13 |                 self.vec.push(v);
   |                 ^^^^^^^^ second mutable borrow occurs here
...
17 |     }
   |     - first borrow ends here

这是由于non-lexical lifetime

作为一种解决方法,我认为我可以重写get()来限制self.find()的范围:

fn get(&mut self, v: i32) -> &mut i32 {
    if let Some(x) = self.find(v) {
        return x;
    }
    self.vec.push(v);
    self.vec.last_mut().unwrap()
}

不幸的是,这不起作用:

error[E0499]: cannot borrow `self.vec` as mutable more than once at a time
  --> test.rs:13:9
   |
10 |         if let Some(x) = self.find(v) {
   |                          ---- first mutable borrow occurs here
...
13 |         self.vec.push(v);
   |         ^^^^^^^^ second mutable borrow occurs here
14 |         self.vec.last_mut().unwrap()
15 |     }
   |     - first borrow ends here

我无法理解为什么。

0 个答案:

没有答案