【发布时间】:2015-06-17 03:56:22
【问题描述】:
我每次使用 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 之后,我认为这会起作用。它编译,但在运行时恐慌。
如何在迭代同一个向量时引用一个向量?有没有更好的数据结构可以让我这样做?
【问题讨论】:
标签: rust