我有一个结构体(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);
Bar
结构体及其所有数据,还有一些BarRef
新类型,我必须在其中一个上实现,具体取决于某个方法的工作方式。无论如何,您介意再详细说明一下何时(或不)这样做可能是一个好主意吗? - GGalizzi