Ric*_*len 3 iterator vector rust borrow-checker
我试图更新向量的每个元素,然后在每次迭代期间借用整个向量,例如:
#![allow(unused)]
#[derive(Debug)]
pub struct Foo {
value: i32,
}
fn main() {
let mut foos: Vec<Foo> = vec![Foo { value: 1 }, Foo { value: 2 }, Foo { value: 3 }];
for foo in &mut foos {
update_single(foo);
//save_all(&foos); <-- this doesn't compile - there's already a mutable borrow
}
}
fn update_single(foo: &mut Foo) {
println!("update_single");
foo.value *= foo.value;
}
fn save_all(foos: &Vec<Foo>) {
println!("save_all:");
for foo in foos {
println!("\t{:?}", foo);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:我将更新后的向量保存为 blob,例如 via serde_json。
for foo in &mut foosfoos将在整个循环中可变地借用整个for。
你可以可变地借用某样东西一次,也可以不可变地借用任意多次,但不能同时借用两者。因此,当您在循环期间可变地借用整个向量时,它不能再次被一成不变地借用,直到循环结束时释放该可变借用为止。
您可以通过仅在循环的一行上可变地借用每个元素来解决此问题,而不是借用整个循环的整个向量。
for i in 0..foos.len() {
update_single(&mut foos[i]);
save_all(&foos);
}
Run Code Online (Sandbox Code Playgroud)
现在我们可变地获取数组中的每一项,并且它每次仅可变地借用该行。