rust 借用检查看起来很聪明,它可以检查和扁平化循环的读写。但我怎样才能绕过它?
以下代码运行良好:
fn main() {
let mut lines = [
vec![1, 2, 3],
vec![4, 5, 6],
vec![7, 8, 9],
];
for i in 0 .. lines.len() {
let line = &lines[i];
for item in line {
// if found odd number, push zero!
if item % 2 == 1 {
lines[i].push(0);
break; // works fine! if comment it, will error!
}
}
}
dbg!(lines);
}
当评论“break”行时,将得到:
error[E0502]: cannot borrow `lines[_]` as mutable because it is also borrowed as immutable
--> src/main.rs:13:17
|
10 | let line = &lines[i];
| --------- immutable borrow occurs here
11 | for &item in line {
| ---- immutable borrow later used here
12 | if item == 5 {
13 | lines[1].push(55);
| ^^^^^^^^^^^^^^^^^ mutable borrow occurs here
error: aborting due to previous error