私はRc<RefCell<Bar>>
フィールドを持つstruct(Foo)を持っていますが、BarはRc<RefCell<Bar>>
によって呼び出されるメソッドを持っています。そのメソッドではFooへの参照を取得し、そのFooにそのRc<RefCell<Bar>>
を設定したいと思います。メソッドを呼び出したバー。メソッドから自己をRc <RefCell<T>として使用する方法はありますか?
は、次のコードを考えてみましょう:
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
に別のパラメータを追加したいものを行うための唯一の方法ですか?私はすでにそれを1人から呼んでいるとき、それは減じているように感じます。
pub fn something(&mut self, rcSelf: Rc<RefCell<Bar>>) {
foo.set_thing(rcSelf);
ありがとう、私は静的な方法で行くと思います。 2番目の選択肢を正しく理解していれば、コードを見るときにnewtypeを作成するのが冗長すぎるように感じます。なぜなら、すべてのデータを含む 'Bar'構造体と、' BarRef' newtypeいくつかの方法がどのように機能するかによって、どちらか一方にインプリメントする必要があります。 いずれにしても、これを行うのが良いアイデアかもしれないときは、ちょっと拡大してもいいですか? – GGalizzi