Explanation needed re Rc, RefCell

I had posted my problem on Stackoverflow but there was no answer. I checked on different resources on the net and was able to solve the problem. Both my question and answer are posted here.

Although my code is working now, I still do not understand why Rc and RefCell are needed. Any explanation will be appreciated.

On SO one of the comments is:

Because you are adding your items to a cloned list, not the one one belonging to your form

Does this part at least make sense? If you clone something and then modify one of the clones, the other clone will not be updated.

When independent parts of your program need access to the same variable, and you cannot simply pass a parameter with a reference to that variable to the all places it is needed, then some sort of sharing is required. In addition, in your case you need shared mutable access, since you need to change the variable. There are multiple ways to do this in Rust.

  • Using Rc/RefCell is one way to have shared mutable access within a single thread. Another approach is to use Cell.
  • Using Arc/Mutex (or RwLock instead of Mutex) is a way to have shared mutable access when there are multiple threads accessing the variable.

Thanks for your explanation. I am reading more about it here.

Also try the Rust book

Rc<T>, the Reference Counted Smart Pointer - The Rust Programming Language

RefCell<T> and the Interior Mutability Pattern - The Rust Programming Language

Shared-State Concurrency - The Rust Programming Language

2 Likes

Thanks for the links.