Single writer, multiple reader RefCell


#1

I have some kind of shared state that’s supposed to be observed by borrowers but only the owner should mutate it. I was wondering if Rust has a standard way of doing that. Currently I’m using RefCell but that means I can mutate the state unintentionally.

Any ideas?


#2

You could wrap it in your own type which only forwards the borrow() method, something like:

use std::cell::{RefCell, Ref};

struct ReadCell<'a, T: 'a>(&'a RefCell<T>);

impl<'a, T: 'a> ReadCell<'a, T> {
    pub fn borrow(&self) -> Ref<T> {
        self.0.borrow()
    }
}

I set this as a reference, and I presume the single writer would hold the actual ownership. You could share it evenly with Rc if that works better for you.


#3

Thanks, this will probably do the trick.