在这种情况下错误意味着什么:
fn main() {
let mut v: Vec<usize> = vec![1, 2, 3, 4, 5];
v[v[1]] = 999;
}
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
--> src/main.rs:3:7
|
3 | v[v[1]] = 999;
| --^----
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
| mutable borrow later used here
我发现索引是通过Index
和IndexMut
特征实现的,v[1]
是*v.index(1)
的句法糖。有了这些知识,我尝试运行以下代码:
use std::ops::{Index, IndexMut};
fn main() {
let mut v: Vec<usize> = vec![1, 2, 3, 4, 5];
*v.index_mut(*v.index(1)) = 999;
}
令我惊讶的是,这完美无缺!为什么第一个片段不起作用,但第二个代码段有效?我理解文档的方式,它们应该是等效的,但显然情况并非如此。
脱糖版本与你拥有的版本略有不同。该行
v[v[1]] = 999;
实际上脱糖到
*IndexMut::index_mut(&mut v, *Index::index(&v, 1)) = 999;
这会导致相同的错误消息,但注释会提示正在发生的事情:
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
--> src/main.rs:7:48
|
7 | *IndexMut::index_mut(&mut v, *Index::index(&v, 1)) = 999;
| ------------------- ------ ^^ immutable borrow occurs here
| | |
| | mutable borrow occurs here
| mutable borrow later used by call
与脱糖版本的重要区别在于评估顺序。在实际进行函数调用之前,将按列出的顺序从左到右计算函数调用的参数。在这种情况下,这意味着评估第一个&mut v
,可变借用v
。接下来,应该评估Index::index(&v, 1)
,但这是不可能的——v
已经被可变借用了。最后,编译器表明函数调用index_mut()
仍然需要可变引用,因此当尝试共享引用时,可变引用仍然有效。
实际编译的版本具有略有不同的计算顺序。
*v.index_mut(*v.index(1)) = 999;
首先,从左到右计算方法调用的函数参数,即 首先评估*v.index(1)
。这会导致usize
,并且v
的临时共享借款可以再次释放。然后,评估index_mut()
的接收器,即v
是可变借用的。这工作正常,因为共享借用已经完成,并且整个表达式都通过了借用检查器。
请注意,编译的版本仅在引入"非词法生存期"后执行此操作。在早期版本的 Rust 中,共享借用将一直存在到表达式结束并导致类似的错误。
在我看来,最干净的解决方案是使用临时变量:
let i = v[1];
v[i] = 999;