How does refcell interact with the borrow checker

Viewed 46

I am trying to wrap my head around the RefCell type, not as a utility, but in terms of it's implementation.

I understand the general idea, a struct that has mutable data inside of it that keeps track of how many active references to that data exist.

but how does it interact with the borrow checker to allow you to mutate the data multiple times?

1 Answers

but how does it interact with the borrow checker to allow you to mutate the data multiple times?

Internally, it doesn't really - it uses unsafe code.

RefCell is a checked wrapper around UnsafeCell, which provides the inner mutability. Its get method returns a *mut pointer to the wrapped type, which can be cast to a &mut reference with an arbitrary lifetime. This, of course, is very unsafe, so it's up to the user to ensure there's no violations of the borrow checker rules with UnsafeCell.

Cell does this by not allowing references to the inner object. RefCell does this via essentially a single-threaded lock, keeping track of whether a reference exists and denying access if so. Mutex and RwLock are similar, but use thread-safe locks.

(As an aside, UnsafeCell IS compiler magic, but for a different reason - it's needed to tell the compiler that an object may change behind an immutable reference. But that doesn't have to do with the borrow checks so much as optimizations.)

Related