以下代码不会编译:
fn test<'a>(index: usize, v: &'a mut Vec<i32>) -> Option<&'a i32> {
{
let t = v.get(index);
if t.is_some() {
return t
}
//return t
}
v.insert(index, index as i32 + 1);
v.get(index)
}
error[E0502]: cannot borrow `*v` as mutable because it is also borrowed as immutable
--> src/main.rs:9:5
|
3 | let t = v.get(index);
| - immutable borrow occurs here
...
9 | v.insert(index, index as i32 + 1);
| ^ mutable borrow occurs here
10 | v.get(index)
11 | }
| - immutable borrow ends here
我认为这段代码没问题,因为不可变借用发生在内部块中。奇怪的是,如果我删除了if子句并且只是返回&#34; t&#34;在内部块中,代码编译得很好。
我在这里遗漏了什么吗?我在Linux上使用Rust 1.22.1。