Ho una struttura (Foo) che ha un campo Rc<RefCell<Bar>>
, Barra ha un metodo che viene chiamato da un Rc<RefCell<Bar>>
, in quel metodo ottiene un riferimento a Foo e vorrei impostare quello Rc<RefCell<Bar>>
in quello Foo al Bar che ha chiamato il metodo.Esiste un modo per utilizzare autonomamente un metodo come Rc <RefCell<T>>?
Si consideri il seguente codice:
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
è l'unico modo per fare quello che voglio aggiungere un altro parametro da Bar::something
accettare un Rc<RefCell<Bar>>
? Sembra ridondante, quando già lo chiamo da uno.
pub fn something(&mut self, rcSelf: Rc<RefCell<Bar>>) {
foo.set_thing(rcSelf);
Grazie, penso che andrò con un metodo statico. Se sto capendo correttamente la seconda scelta, creare un newtype è ancora un po 'troppo ridondante quando guardo il mio codice, dato che avrei la struttura 'Bar' con tutti i suoi dati, e poi qualche newtype' BarRef', e dovrei impiantare l'uno o l'altro a seconda di come funziona un metodo. In ogni caso ti dispiacerebbe ampliare un po 'quando potrebbe (o non) essere una buona idea per fare questo? – GGalizzi