可变借入超出范围但无法重新借入

时间:2018-11-13 18:29:13

标签: rust

当第一次可变借项似乎超出范围时,我很难理解为什么我不能第二次使用v

fn get_or_insert(v: &mut Vec<Option<i32>>, index: usize, default: i32) -> &mut i32 {
    if let Some(entry) = v.get_mut(index) { // <-- first borrow here
        if let Some(value) = entry.as_mut() {
            return value;
        }
    }

    // error[E0502]: cannot borrow `*v` as immutable because it is also borrowed as mutable    
    while v.len() <= index {                // <-- compiler error here
        v.push(None);
    }

    // error[E0499]: cannot borrow `*v` as mutable more than once at a time
    let entry = v.get_mut(index).unwrap();  // <-- compiler error here
    *entry = Some(default);
    entry.as_mut().unwrap()
}

playground link

我的变量作用域是否错误,还是借位检查器使我免受未看到的东西的侵害?

编辑:启用NLL的错误消息非常好:

error[E0502]: cannot borrow `*v` as immutable because it is also borrowed as mutable
  --> src/main.rs:10:11
   |
3  | fn get_or_insert(v: &mut Vec<Option<i32>>, index: usize, default: i32) -> &mut i32 {
   |                     - let's call the lifetime of this reference `'1`
4  |     if let Some(entry) = v.get_mut(index) {
   |                          - mutable borrow occurs here
5  |         if let Some(value) = entry.as_mut() {
6  |             return value;
   |                    ----- returning this value requires that `*v` is borrowed for `'1`
...
10 |     while v.len() <= index {
   |           ^ immutable borrow occurs here

1 个答案:

答案 0 :(得分:1)

关键点在于,即使使用NLL,返回值的生存期也会跨越整个函数。在确定下面的代码中是否可以访问v引用时,不会考虑函数在第4行提前返回的事实。

@Stargateur建议的解决方法是在访问元素之前根据需要增大向量:

fn get_or_insert(v: &mut Vec<Option<i32>>, index: usize, value: i32) -> &mut i32 {
    if v.len() < index {
        v.resize(index + 1, None);
    }
    v[index].get_or_insert(value)
}

playground link

Here's where I used the technique in the final code.