有什么方法可以将方法中的self用作Rc<RefCell<T>>?

  • 本文关键字:方法 Rc 用作 RefCell self rust
  • 更新时间 :
  • 英文 :


我有一个具有Rc<RefCell<Bar>>字段的结构(Foo),Bar有一个由Rc<RefCell<Bar>>调用的方法,在该方法中它获得了对Foo的引用,我想将该Rc<RefCell<Bar>>设置在该Foo中到调用该方法的Bar。

请考虑以下代码:

struct Foo {
    thing: Rc<RefCell<Bar>>,
}
struct Bar;
impl Foo {
    pub fn set_thing(&mut self, thing: Rc<RefCell<Bar>>) {
       self.thing = thing;
    }
}
impl Bar {
    pub fn something(&mut self) {
        // Things happen, I get a &mut to a Foo, and here I would like to use this Bar reference
        // as the argument needed in Foo::set_thing            
    }
}
// Somewhere else
// Bar::something is called from something like this:
let my_bar : Rc<RefCell<Bar>> = Rc::new(RefCell::new(Bar{}));
my_bar.borrow_mut().something();
// ^--- I'd like my_bar.clone() to be "thing" in the foo I get at Bar::something

接受Rc<RefCell<Bar>> Bar::something,我想添加另一个参数的唯一方法是什么?感觉是多余的,当我已经从一个调用它时。

    pub fn something(&mut self, rcSelf: Rc<RefCell<Bar>>) {
        foo.set_thing(rcSelf);

这里有两个主要选择:

  • 使用静态方法:

    impl Bar {
        pub fn something(self_: Rc<RefCell<Bar>>) {
            …
        }
    }
    Bar::something(my_bar)
    
  • 隐藏你正在使用Rc<RefCell<X>>的事实,用单字段Rc<RefCell<X>>将其包装在一个新类型中;然后其他类型可以使用这个新类型而不是Rc<RefCell<Bar>>你可以使这个something方法适用于self。这可能是也可能不是一个好主意,具体取决于您如何使用它。没有进一步的细节,很难说。

最新更新