在这种情况下,错误意味着什么:
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;
关于rust - 嵌套数组索引中的 "cannot borrow as immutable because it is also borrowed as mutable"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59145661/