在循环内借用向量
我试图更新向量的每个元素,然后在每次迭代期间借用整个向量,例如:
#![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
。
I'm trying to update each element of a vector and then borrow the entire vector during each iteration, ex:
#![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);
}
}
Note: I'm saving the updated vector as a blob e.g. via serde_json
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
for foo in &mut foos
将在整个for
循环中可变地借用整个foos
。你可以可变地借用某样东西一次,也可以不可变地借用任意多次,但不能同时借用两者。因此,当您在循环期间可变地借用整个向量时,它不能再次被一成不变地借用,直到循环结束时释放该可变借用为止。
您可以通过仅在循环的一行上可变地借用每个元素来解决此问题,而不是借用整个循环的整个向量。
现在我们可变地获取数组中的每一项,并且它每次仅可变地借用该行。
for foo in &mut foos
will borrow the entirety offoos
mutably throughout the entirefor
loop.You can either borrow something mutably once or immutably any number of times, but not both. So, when you borrow the entire vector mutably for the duration of the loop, it can't be immutably borrowed again until you let go of that mutable borrow when the loop finishes.
You can get around this by borrowing each element mutably only on one line of the loop, rather than borrowing the entire vector for the entire loop.
Now we mutably get each item in the array, and it only mutably borrows each time on that one line.