每次使用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());
}
}
Run Code Online (Sandbox Code Playgroud)
读完之后RefCell我觉得这样可行.它编译,但在运行时恐慌.
在迭代同一向量时如何引用向量?是否有更好的数据结构允许我这样做?
你的程序很恐慌,因为你试图Vec在同一时间可变地和不可变地借用:这是不允许的.
你需要做的只是包装Strings in RefCell.这允许您在迭代时改变字符串Vec.
use std::cell::RefCell;
struct Res {
name: RefCell<String>,
}
impl Res {
fn new(name: &str) -> Res {
Res {
name: RefCell::new(name.to_string()),
}
}
// I don't need all_res to be mutable
fn normalize(&self, all_res: &Vec<Res>) {
// [...] Iterate through all_res and update self.name
*self.name.borrow_mut() = "foo".to_string();
}
}
fn main() {
let res = vec![Res::new("res1"), Res::new("res2")];
for r in res.iter() {
r.normalize(&res);
}
println!("{}", *res[0].name.borrow());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1067 次 |
| 最近记录: |