【问题标题】:Rc/RefCell with parent of same struct具有相同结构的父级的 Rc/RefCell
【发布时间】: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);
    }
}

因此,正如您在代码中看到的,我无法访问我的父状态,有什么建议吗?

谢谢

【问题讨论】:

    标签: rust rc refcell


    【解决方案1】:

    尽量避免在 Rust 中编写“面向对象”的代码。更喜欢组合而不是继承。如果您使用Rcs 来表示树状结构,请小心您指向“父母”。如果父母也是Rc,您将有内存泄漏,因为这会产生一个循环。要打破这些,您可以使用Weak 引用。也许阅读本书的secion 会对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多