我需要迭代和修改
for
循环中的元素,但我还必须将 Vec
传递到修改它的函数中。有没有更好的方法用 Rust 编写这个?
最小可重现代码:
fn main() {
let mut x: Vec<Ex> = Vec::new();
for _ in 0..10 {
x.push(Ex {});
}
for e in &mut x {
e.do_stuff(&x)
}
}
struct Ex {}
impl Ex {
pub fn do_stuff(&mut self, x: &Vec<Ex>) {
for _ in x {
println!("Yay!")
}
}
}
编译器消息:
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
--> src\main.rs:8:20
|
7 | for e in &mut x {
| ------
| |
| mutable borrow occurs here
| mutable borrow later used here
8 | e.do_stuff(&x)
| ^^ immutable borrow occurs here
可使用间接法求解,例如
RefCell
:
use std::cell::RefCell;
fn main() {
let x: RefCell<Vec<Ex>> = RefCell::new(Vec::new());
for _ in 0..10 {
x.borrow_mut().push(Ex {});
}
for e in x.borrow_mut().iter_mut() {
e.do_stuff(&(x.borrow()))
}
}
struct Ex {}
impl Ex {
pub fn do_stuff(&mut self, x: &Vec<Ex>) {
for _ in x {
println!("Yay!")
}
}
}