Is there a way that I could use on my own from a method like Rc <RefCell <T>>?

I have a structure (Foo) that has a field Rc<RefCell<Bar>> , Bar has a method that is called Rc<RefCell<Bar>> , in this method it gets a link to Foo, and I would like to establish that Rc<RefCell<Bar>> in is that Foo is in Bar, which called the method.

Consider the following code:

 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 

The only way to do what I want to add to Bar::something another parameter to accept Rc<RefCell<Bar>> ? He feels eloquent when I call him from one already.

  pub fn something(&mut self, rcSelf: Rc<RefCell<Bar>>) { foo.set_thing(rcSelf); 
+6
source share
1 answer

There are two main options here:

  • Use the static method:

     impl Bar { pub fn something(self_: Rc<RefCell<Bar>>) { … } } Bar::something(my_bar) 
  • Hide the fact that you are using Rc<RefCell<X>> , wrapping it with a new type with a single field Rc<RefCell<X>> ; then other types can use this new type, not 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. It’s hard to say without further details.

+2
source

Source: https://habr.com/ru/post/980729/


All Articles