rust borrow check 看起来很聪明,它可以检查和平整循环的读写。但我怎样才能绕过它呢?
rust borrow check looks very smart , it can check and flat reads and writes of loop. but how can I bypass it?
rust borrow check 看起来很聪明,可以检查和平整循环的读写。但是我怎样才能绕过它呢?
以下代码运行良好:
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
您没有绕过借用检查器。您考虑它告诉您的内容并重新考虑您的程序以匹配。
这里告诉你不能修改当前正在迭代的东西(r^w 原则),所以不要那样做。如果您想在每行中添加与奇数一样多的零,请执行以下操作:计算该行中的奇数,然后添加那么多零:
use std::iter::repeat;
fn main() {
let mut lines = [
vec![1, 2, 3],
vec![4, 5, 6],
vec![7, 8, 9],
];
for line in lines.iter_mut() {
let odds = line.iter().filter(|it| *it % 2 == 0).count();
line.extend(repeat(0).take(odds));
}
dbg!(lines);
}
rust borrow check 看起来很聪明,可以检查和平整循环的读写。但是我怎样才能绕过它呢?
以下代码运行良好:
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
您没有绕过借用检查器。您考虑它告诉您的内容并重新考虑您的程序以匹配。
这里告诉你不能修改当前正在迭代的东西(r^w 原则),所以不要那样做。如果您想在每行中添加与奇数一样多的零,请执行以下操作:计算该行中的奇数,然后添加那么多零:
use std::iter::repeat;
fn main() {
let mut lines = [
vec![1, 2, 3],
vec![4, 5, 6],
vec![7, 8, 9],
];
for line in lines.iter_mut() {
let odds = line.iter().filter(|it| *it % 2 == 0).count();
line.extend(repeat(0).take(odds));
}
dbg!(lines);
}