每次使用 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我认为这会起作用。它可以编译,但在运行时会出现恐慌。
如何在迭代同一向量时引用向量?有没有更好的数据结构可以让我做到这一点?
你的程序会因为你试图借用而发生恐慌Vec
同时可变和不可变:这是不允许的。
你需要做的只是包裹String
s 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());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)