Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 132 ยท Smart Pointers and Memory

Interior Mutability: Cell and RefCell

Learn Rust interior mutability with Cell, RefCell, OnceCell and LazyCell: runtime borrow checking, BorrowMutError panics, Rc<RefCell<T>> graphs and when to avoid them.

Rust's borrow checker enforces one rule at compile time: at any moment you may have many shared references (&T) or exactly one mutable reference (&mut T), never both. Usually that is exactly what you want. But sometimes the compile-time rule is too blunt. A cache that fills itself on first use, a counter inside a struct you only hold by &, several owners of an Rc that all need to change the same value: all of these look like "mutation through a shared reference", which the compiler forbids.

Interior mutability is the escape hatch. A type with interior mutability lets you change its contents through &self, because it enforces the safety rules itself, either by never handing out references (Cell) or by checking at runtime (RefCell). Inside, these types use a little unsafe code, but the API they expose is safe. This lesson covers Cell, RefCell, and the lazy-initialization cells OnceCell and LazyCell, and ends with the thread-safe cousins.

The problem

Rust Mutating through &self (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

rustc reports error E0594: "cannot assign to self.hits, which is behind a & reference", with the help to consider changing this to be a mutable reference (&mut self). Often that is the right fix. But if record must work on a shared &Counter (many readers, one shared logger, a trait method fixed to &self) you need interior mutability.

Cell: copy in, copy out

Cell<T> stores a value and never gives out a reference to it. You can only get a copy, set a new value, replace it, or take it out. Because no reference to the inside ever exists, mutation cannot invalidate anything. There is no runtime cost and no way to panic.

Rust Cell as a hit counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

get() needs T: Copy. For types such as String you cannot copy out, so you use take() (leaves the default value) or replace(new) (gives you the old one). Cell is the best choice for small Copy data: counters, flags, ids, cached numbers.

Pitfall: Cell is for plain values. If you find yourself wanting to borrow the contents (to call a method on a Vec inside), you need RefCell.

RefCell: borrow rules checked at runtime

RefCell<T> does let you borrow the contents. borrow() gives a Ref<T> (like &T) and borrow_mut() gives a RefMut<T> (like &mut T). The same rule applies, many readers or one writer, but it is checked while the program runs. The cell keeps a counter of active borrows; break the rule and the program panics.

Rust RefCell basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The guards (Ref, RefMut) release their borrow when they are dropped. A temporary such as log.borrow_mut().push(...) is dropped at the end of the statement, so the next line can borrow again. Guards you store in a variable live until the end of the scope (or an explicit drop).

The runtime panic

Hold a borrow_mut() guard and ask for another borrow, and you break the rule:

Rust BorrowMutError (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program compiles (the compiler cannot see the problem) and then panics at the borrow_mut line with the message RefCell already borrowed and exit code 101. The error type behind it is BorrowMutError; asking for a shared borrow while a mutable one exists gives BorrowError. This is the price of RefCell: mistakes that &mut would catch at compile time become panics at runtime.

Two defences:

  1. Keep borrows short. Do not store guards in long-lived variables. Prefer one-liners like cell.borrow_mut().push(x).
  2. Use the fallible versions when a conflict is possible: try_borrow() and try_borrow_mut() return Result.
Rust try_borrow_mut instead of panicking

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A subtle trap: guards living too long

A RefMut that is still alive when you call code that borrows the same cell again is the most common real-world RefCell panic. Keep the decision separate from the mutation:

Rust Drop the guard before calling back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Each borrow() here is a temporary that ends before the next one starts.

Rc<RefCell>: shared and mutable

Rc gives several owners; RefCell allows mutation. Together they make the classic single-threaded shared-mutable-state pattern. Think of a document model shared between a view and an editor, or nodes of a graph.

Rust A tiny graph with shared mutable nodes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice we never let a borrow() guard on start stay alive while we mutate neighbours: the vector of Rc clones is collected first. Skipping that step is how graph code ends in BorrowMutError.

Cycles in such graphs leak, as discussed in Rc, Arc and Shared Ownership; use Weak for back-references.

OnceCell: write once, read many

OnceCell<T> (stable in std::cell) holds a value that is set at most once. Before it is set, get() returns None; afterwards it returns Some(&T) forever, and no RefCell guard is needed. get_or_init(|| ...) computes the value on first use. Perfect for expensive derived data in a struct you hold by &self.

Rust OnceCell caches an expensive value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The "computing" message appears once. A second set returns Err(2), handing the rejected value back to you.

LazyCell: initialize on first access

LazyCell<T, F> (and its thread-safe sibling LazyLock) stores the initializer next to the value and runs it automatically on first dereference. It is the lazy let: you declare how, and the first use does it.

Rust LazyCell runs its closure on first use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The building message appears between the first two println! lines, exactly once. For global state shared across the program, use LazyLock in a static, which is the thread-safe version (static CONFIG: LazyLock<Config> = LazyLock::new(...)).

Which one do I use?

Type Gives out Checked Cost Good for
Cell<T> copies, never references compile time (no references exist) none counters, flags, small Copy data
RefCell<T> Ref / RefMut guards runtime (can panic) a borrow counter collections, structs behind Rc
OnceCell<T> &T after one write write-once check a flag memoization, deferred setup
LazyCell<T> &T via deref write-once a flag lazy values with the initializer attached

All four are not thread-safe (!Sync): the compiler refuses to share them between threads. For threads use Mutex<T>/RwLock<T> (locks), OnceLock/LazyLock (write-once), or atomics for plain integers and flags. The pairings are:

  • Rc<RefCell<T>> on one thread, Arc<Mutex<T>> on many.
  • Cell<u32> on one thread, AtomicU32 on many.
  • OnceCell / LazyCell on one thread, OnceLock / LazyLock on many.

A Mutex preview with the same shape as the Rc<RefCell> examples:

Rust The thread-safe counterpart: Mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A Mutex lock call blocks (waits) instead of panicking when another thread holds it, which is the same idea as RefCell's rule but across threads.

Design advice

  • Try regular borrowing first. Interior mutability moves errors from compile time to runtime. Restructure with &mut, pass values around, or split a struct into two parts before you reach for a cell.
  • Keep the cell small and the borrows short. A RefCell per field is often easier to reason about than a RefCell around a whole big struct.
  • Hide it behind methods. Expose fn add(&self, x) rather than letting callers see .borrow_mut() everywhere; then the borrow scope stays inside one function you can audit.
  • Avoid re-entrancy. Callbacks that run while you hold a guard and then call back into the same object are the number one source of BorrowMutError.
  • Cells inside Rc can leak through cycles; use Weak.

RefCell does not remove the aliasing rules; it moves their enforcement to runtime. A RefCell program that panics with a borrow error has the same bug that &mut would have rejected at compile time.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does interior mutability allow?

    Types like Cell and RefCell enforce safety themselves (no references handed out, or a runtime borrow counter), so their mutation methods take &self.
  2. 2. Which statement about Cell<T> is true?

    Cell has no borrow tracking because it never exposes references: get copies out (T: Copy), set/replace/take move values.
  3. 3. What happens if you call borrow_mut() on a RefCell while a borrow() guard from the same cell is still alive?

    RefCell checks the borrowing rules while running. Violating them panics (BorrowMutError); try_borrow_mut returns an Err instead.
  4. 4. How do you avoid a panic when a borrow conflict is possible?

    The try_ variants return Err(BorrowError or BorrowMutError) instead of panicking, so you can handle the conflict.
  5. 5. What is OnceCell good for?

    OnceCell holds a write-once value. After the first set (or get_or_init), get returns Some(&T) without any guard.

Summary

  • Interior mutability lets you mutate through &self; the type enforces safety instead of the compiler.
  • Cell<T> copies values in and out (get, set, replace, take): no references, no panics, no overhead.
  • RefCell<T> hands out Ref/RefMut guards and checks the many-readers-or-one-writer rule at runtime; violations panic with BorrowMutError/BorrowError, and try_borrow(_mut) returns a Result instead.
  • Keep guards short-lived and avoid calling back into code that borrows the same cell.
  • Rc<RefCell<T>> is the single-threaded shared-mutable pattern; Arc<Mutex<T>> is its multi-threaded form.
  • OnceCell and LazyCell provide write-once and lazy initialization; OnceLock and LazyLock are the thread-safe versions.
  • Prefer ordinary borrowing and restructuring; use cells when sharing or &self APIs truly require them.

Next: Drop and RAII