What's difference between RefCell<Rc<T>> and Rc<RefCell<T>>?

can anybody tell me the difference between RefCell<Rc> and Rc<RefCell>, and in what scenarios respectively?

1 Like

Rc gives you a reference counted version of Box. RefCell, using interior mutability, gives you runtime checked borrowing. Rc itself doesn't allow mutable borrows to what it is enclosing. Thus Rc<T> cannot directly be used for things you want to mutate. For that, you need to enclose the T in a RefCell, thus giving the final type of Rc<RefCell<T>>.
RefCell<Rc<T>> by itself isn't really useful, since although the RefCell gives you runtime checked mutable borrows, since Rc doesn't allow mutation, you get nothing out of it.

3 Likes

RefCell<Rc<T>> would be a pretty niche data type, it will almost always be Rc<RefCell<T>>

Rc provides a reference counted stable memory address for the type it wraps. RefCell allows you to mutate the type it wraps without an exclusive reference &mut T.

Rc<RefCell<T>> means you have a shared T that can be mutated via one of the Rc smart pointers

RefCell<Rc<T>> means you can store a new Rc smart pointer to the variable without an exclusive reference. It doesn't allow you to mutate T itself since Rc only allows you to get shared references &T.

1 Like

It might be useful if you need to replace the Rc behind shared access …
… after all, a type akin to an optimized RwLock<Arc<T>> is the whole premise of this popular crate (though one could then argue that perhaps this pattern is more common and/or useful in multi-threaded scenarios).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.