有没有办法在一个方法中将self用作Rc<RefCell<T>>?

13

我有一个结构体(Foo),其中包含一个 Rc<RefCell<Bar>> 字段,Bar 有一个被 Rc<RefCell<Bar>> 调用的方法,在该方法中,它会得到对 Foo 的引用,并且我希望将调用该方法的 Bar 对象设置为该 Foo 中的那个 Rc<RefCell<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

我想知道是否唯一的方法是向Bar::something添加另一个接受 Rc<RefCell<Bar>> 的参数?感觉有些冗余,因为我已经从其中一个调用了它。

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

8

这里有两个主要选择:

  • Use a static method:

    impl Bar {
        pub fn something(self_: Rc<RefCell<Bar>>) {
            …
        }
    }
    
    Bar::something(my_bar)
    
  • Conceal the fact that you’re using Rc<RefCell<X>>, wrapping it in a new type with the single field Rc<RefCell<X>>; then other types can use this new type rather than Rc<RefCell<Bar>> and you can make this something method work with self. This may or may not be a good idea, depending on how you use it. Without further details it’s hard to say.


谢谢,我想我会选择静态方法。如果我正确理解第二个选项,那么创建一个新类型仍然感觉有点冗余,因为我会有Bar结构体及其所有数据,还有一些BarRef新类型,我必须在其中一个上实现,具体取决于某个方法的工作方式。无论如何,您介意再详细说明一下何时(或不)这样做可能是一个好主意吗? - GGalizzi
第二种方法也很有效,对用户来说更加简洁。但是对于一个简单的问题来说,它感觉需要写很多额外的代码。 - Mark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接