Rust 我有没有办法从一个方法中使用self作为Rc<;RefCell<;T>>;?
我有一个结构(Foo),它有一个Rust 我有没有办法从一个方法中使用self作为Rc<;RefCell<;T>>;?,rust,Rust,我有一个结构(Foo),它有一个Rc字段,Bar有一个被Rc调用的方法,在该方法中,它获取对Foo的引用,我想将该Foo中的Rc设置为调用该方法的Bar 考虑以下代码: struct Foo { thing: Rc<RefCell<Bar>>, } struct Bar; impl Foo { pub fn set_thing(&mut self, thing: Rc<RefCell<Bar>>) { se
Rc
字段,Bar有一个被Rc
调用的方法,在该方法中,它获取对Foo的引用,我想将该Foo中的Rc
设置为调用该方法的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
这里有两个主要选择:
- 使用静态方法:
impl Bar { pub fn something(self_: Rc<RefCell<Bar>>) { … } } Bar::something(my_bar)
impl条{ pub fn某物(self\urc){ … } } 酒吧:某物(我的酒吧)
- 隐藏您正在使用的
,用一个字段Rc
将其包装成一个新类型;然后其他类型可以使用此新类型而不是Rc
,并且您可以使此Rc
方法与
一起工作。这可能是一个好主意,也可能不是一个好主意,这取决于你如何使用它。没有进一步的细节,很难说self
Bar
struct及其所有数据,然后使用一些BarRef
newtype,我必须根据某种方法的工作方式来实现其中一种。在任何情况下,您是否介意在什么时候扩展一下,这样做可能(或不是)是一个好主意?第二种方法也很有效,对用户来说更简洁。但对于一个简单的问题,它感觉像是相当多的额外代码。
impl Bar {
pub fn something(self_: Rc<RefCell<Bar>>) {
…
}
}
Bar::something(my_bar)