【发布时间】:2022-10-13 23:50:03
【问题描述】:
我正在尝试将一些面向对象的代码带入 rust,在遇到这种情况之前还可以。
所以我有这3个结构
struct A {
root: Rc<RefCell<B>>,
}
struct B {
parent: Rc<RefCell<B>>,
c_lst: Vec<C>
value: u32
}
struct C {
parent: Rc<RefCell<B>>,
b_lst: Vec<Rc<RefCell<B>>>,
end: bool
}
我想要实现的是让一个主结构(此处为A)拥有结构B 的根。
B 和 C 需要以只读方式访问父值,但在第一个 Rc 出现的地方它们需要是可变的。
所以在开始时这个函数被调用
impl A {
fn register(&mut self) {
for c in self.root.borrow_mut().c_lst {
c.parent = self.root.clone();
}
}
}
然后我在A 上使用更新功能
impl A {
fn update(&mut self) {
self.root.borrow_mut().update();
}
}
impl B {
fn update(&mut self) {
for c in &mut self.c_lst {
c.update();
}
}
}
impl C {
fn update(&mut self) {
// Fail because parent is already borrowed to call this update fn
if self.parent.try_borrow().unwrap().value == 0 {
// Do stuff
}
if some_condition {
self.spawn_b();
}
for b in &self.b_lst {
b.borrow_mut().update();
}
}
// This, infinite loop in this state, but it's for the example
fn spawn_b(&mut self) {
let b = Rc::new(RefCell::new(B::new()));
b.borrow_mut().parent = self.parent.clone();
if !self.end {
b.borrow_mut().c_lst = vec![C::new(b.clone()), C::new(b.clone())];
for c in b.borrow_mut().c {
c.spawn_b();
}
}
self.b_lst.push(b);
}
}
因此,正如您在代码中看到的,我无法访问我的父状态,有什么建议吗?
谢谢
【问题讨论】: