每次我使用Rust时,都会遇到与所有权/借用相关的类似问题,因此这里是最简单的代码片段,展示了我的常见问题:
use std::cell::RefCell;
struct Res {
name: String,
}
impl Res {
fn new(name: &str) -> Res {
Res {
name: name.to_string(),
}
}
// I don't need all_res to be mutable
fn normalize(&mut self, all_res: &Vec<Res>) {
// [...] Iterate through all_res and update self.name
self.name = "foo".to_string();
}
}
fn main() {
let res = RefCell::new(vec![Res::new("res1"), Res::new("res2")]);
for r in res.borrow_mut().iter_mut() {
// This panics at runtime saying it's
// already borrowed (which makes sense, I guess).
r.normalize(&*res.borrow());
}
}
阅读了有关RefCell
的内容后,我认为这会起作用。它可以编译,但在运行时会发生崩溃。
在迭代相同向量时如何引用向量?是否有更好的数据结构允许我这样做?
unsafe
的舱门,当你理解所有权规则时已经很难了,但如果你还没有内化它们... - Matthieu M.