How to achieve interior mutability using Rc and RefCell

My demo is here

Because Role struct contains a Vec, so I can't impl a Copy trait for it.I want to achieve the goals that when modifying role1, the role1 in h and role2 get updated.

You're trying to call the into_inner method from RefCell, which takes ownership of the refcell and destroys it. However since you're storing it in an Rc, you cannot take it out, since there might be several Rc-pointers to that same RefCell, and destroying it would invalidate the others.

Here Playground every vec's role1 is updated. Here is a good explanation of using Rc<RefCell<T>> Why this code doesn't panic? ignore the title.

Interesting, Your code and my code are almost the same, the only difference is I created a new variable named new_role1 while yours not. I will try this, thanks.

1 Like

With your help here I think I can solve this issue today. :grinning:

1 Like

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