在循环中借用一个向量
Borrow a vector inside a loop
我正在尝试更新向量的每个元素,然后在每次迭代期间借用整个向量,例如:
#![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);
}
}
注意:我将更新后的向量保存为一个 blob,例如通过 serde_json
.
for foo in &mut foos
将在整个 for
循环中可变地借用整个 foos
。
您可以可变地借用一次或不可变地借用任意次数,但不能同时借用两次。因此,当您在循环期间可变地借用整个向量时,它不能再次不变地借用,直到您在循环结束时放开该可变借用。
您可以通过仅在循环的一行上可变地借用每个元素来解决这个问题,而不是为整个循环借用整个向量。
for i in 0..foos.len() {
update_single(&mut foos[i]);
save_all(&foos);
}
现在我们可变地获取数组中的每一项,它每次只可变地借用那一行。
我正在尝试更新向量的每个元素,然后在每次迭代期间借用整个向量,例如:
#![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);
}
}
注意:我将更新后的向量保存为一个 blob,例如通过 serde_json
.
for foo in &mut foos
将在整个 for
循环中可变地借用整个 foos
。
您可以可变地借用一次或不可变地借用任意次数,但不能同时借用两次。因此,当您在循环期间可变地借用整个向量时,它不能再次不变地借用,直到您在循环结束时放开该可变借用。
您可以通过仅在循环的一行上可变地借用每个元素来解决这个问题,而不是为整个循环借用整个向量。
for i in 0..foos.len() {
update_single(&mut foos[i]);
save_all(&foos);
}
现在我们可变地获取数组中的每一项,它每次只可变地借用那一行。