Search code examples
rustrefcell

Is RefCell ever useful on its own


It might seem like a strange question, but "interior mutability" cells in Rust are always explained and used in a context where they're used together with some kind of shared pointer. And indeed it seems pretty useless on its own, since you get interior mutability with no way to share it.

So here is my question: Is it ever useful ? And if it is not (and never used), what's the point of not providing a RefCell that is also a shared pointer ?


Solution

  • The RefCell is not always directly inside the Rc. For example, this kind of struct can be quite useful:

    use std::cell::RefCell;
    
    struct SharedVec<T> {
        inner: RefCell<Vec<T>>,
    }
    
    impl<T> SharedVec<T> {
        fn push(&self, value: T) {
            self.inner.borrow_mut().push(value);
        }
        fn pop(&self) -> Option<T> {
            self.inner.borrow_mut().pop()
        }
    }
    

    And then, you might have an Rc<SharedVec<T>>.