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

GGa*_*zzi 8 rust

我有一个具有Rc<RefCell<Bar>>字段的结构(Foo),Bar有一个被a调用的方法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
Run Code Online (Sandbox Code Playgroud)

是唯一的方法做我想要添加另一个参数来Bar::something接受一个Rc<RefCell<Bar>>?当我已经从一个人那里打电话时,它感觉很简单.

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

Chr*_*gan 7

这里有两个主要选择:

  • 使用静态方法:

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