Mutate Option RefCell: Cannot borrow as mutable

I have a struct (Foo) with an Optional field, that contains a Refcell to an Rc to another struct (Spam).
When trying to call a mutating method on the Spam struct, I cannot seem to borrow this field at al.

I feel like I've totally gone down a weird path here, and am probably too close to the trees to see the forest so to speak. Would appreciate any suggestions to improve this?

The field has to be an Option since it may be None or Some, and it has to be an RC. The RefCell seemed like a good idea to mutate the inner contents. Maybe I've got the ordering wrong?

Thank you in advance!

You can do this:

Rc::get_mut(&mut *self.spam.as_ref().unwrap().borrow_mut()).unwrap().load()

but I don't think that's what you want.

In general you don't mutate a value inside a Rc that's why the combo Rc<RefCell<T>> is popular, it allows you to get a shared reference from the Rc and then possibly mutate it through the RefCell. The book talk about this pattern is this chapter for more information.
I made a playground with the change.

Thanks! Yes you're right, indeed I meant to use Rc<RefCell<T>> not <RefCell<Rc<T>>. I flipped them accidentally mentally and just didn't think about it.

Cheers!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.