【发布时间】:2020-07-09 10:09:42
【问题描述】:
关于 Rust 的error[E0502] 的问题有很多答案,但我无法真正理解一个特定的案例。我有一个struct,它的impl 方法是这样的:
struct Test {
test_vec: Vec<i32>,
}
impl Test {
// other methods...
fn test(&mut self) -> i32 {
self.test_vec.swap(0, self.test_vec.len() - 1);
// other operations...
}
}
试图编译立即导致错误:
错误[E0502]:不能将
self.test_vec借为不可变,因为它也借为可变
self.test_vec.swap(0, self.test_vec.len() - 1);
------------- ---- ^^^^^^^^^^^^^ immutable borrow occurs here
| |
| mutable borrow later used by call
mutable borrow occurs here
谁能解释一下为什么?看起来我并没有试图在那里借用self.test_vec,我正在传递len() 调用的usize 类型结果。另一方面:
fn test(&mut self) -> i32 {
let last_index = self.test_vec.len() - 1;
self.test_vec.swap(0, last_index);
// other operations...
}
使用临时变量,它按预期工作,让我认为len() 调用以某种方式被评估在它到达swap,因此被借用?我是不是因为语法糖而看不到东西?
【问题讨论】: