【发布时间】:2018-03-29 04:06:08
【问题描述】:
我正在遍历一个向量,我想更改其中一个元素。
fn main() {
let mut vector = vec![1, 2, 3, 4];
for (i, el) in vector.iter().enumerate() {
if i == 0 {
continue;
}
vector[i - 1] += el
}
}
这给了我编译器错误:
error[E0502]: cannot borrow `vector` as mutable because it is also borrowed as immutable
--> src/main.rs:8:9
|
4 | for (i, el) in vector.iter().enumerate() {
| ------ immutable borrow occurs here
...
8 | vector[i - 1] += el
| ^^^^^^ mutable borrow occurs here
9 | }
| - immutable borrow ends here
我明白为什么会出现这个错误。我在枚举范围的生命周期内借用向量作为不可变的,然后尝试改变该范围内的内部,从而打破借用规则。我只是不明白如何正确地做到这一点。我想我需要可变地借用枚举?
我尝试了mut、&mut 的各种组合,但每种组合都遇到了不同的编译器错误。我知道我可以将其设为 Vec<Cell<i32>> 并以这种方式改变内容,但对于这样一个简单的示例来说,这似乎有点过头了。
【问题讨论】:
标签: rust