Ownership in Practice · 18 min · free lesson

Interior Mutability

Move a checked borrow rule to runtime.

Core idea

Cell and RefCell allow mutation behind an immutable outer binding.

RefCell permits multiple simultaneous read guards but blocks a read while a write guard is active.
RefCell checks the shared-or-exclusive rule at runtime.

Understand it

Cell and RefCell allow mutation behind an immutable outer binding. RefCell enforces the same shared-or-exclusive rule at runtime and panics if code violates it.

Normal Rust borrowing checks shared readers and exclusive writers at compile time. RefCell<T> moves that particular check to runtime for single-threaded code. An immutable binding can contain a RefCell<Vec<_>>, and calling borrow_mut() can still modify the vector inside. The outer reference is immutable; the cell enforces the inner access rule with a runtime borrow counter. It does not turn conflicting access into something safe to ignore.

In the sample, the temporary mutable guard from borrow_mut() ends after push, so a later borrow() is allowed. Keep a RefMut guard in a variable and try calling borrow() before dropping that guard: the program panics because a writer and reader would overlap. The fallible try_borrow() and try_borrow_mut() variants return an error instead of panicking, which can be useful when a conflict is a normal possibility. Hold guards for as short a period as practical.

RefCell<T> is not the tool for sharing mutable data across threads; types such as Mutex<T> address synchronization there. Use interior mutability when the surrounding API legitimately needs a shared outer reference while an inner value changes, such as a test spy or a local cache. Do not use it to escape a confusing borrow error before understanding the original ownership model. Runtime checks trade earlier compiler feedback for a more flexible access pattern, so that trade should be intentional.

Read the code

use std::cell::RefCell;
let notes = RefCell::new(Vec::new());
notes.borrow_mut().push("ready");
println!("{}", notes.borrow().len());

The example makes the contract visible in code.

Practise this code in Playground ↗

Try it

Find where the guard from borrow_mut() starts and ends, and where the check happens.

What success looks like: You can say why the later borrow() succeeds, and what would make it panic.

Check your understanding

Where does RefCell check borrowing?

Reveal the answer
  1. At runtime
  2. In Cargo.lock
  3. It does not check

Correct: At runtime.

Go deeper

Common misconception: “RefCell switches off the borrow rules.”

It enforces the same shared-or-exclusive rule, only at runtime. A borrow() while a RefMut guard is alive panics, and try_borrow() returns an error instead.

  1. Spot the guard: notes is not mut, yet borrow_mut() returns a guard that lets push change the Vec. That temporary guard ends with the statement.
  2. Predict before checking: Predict what notes.borrow().len() prints. Then hold let guard = notes.borrow_mut(); and predict what notes.borrow() does while guard is alive.
  3. Compare with evidence: The original prints 1. With the guard held it still compiles, and then panics at runtime with an already-borrowed message.

Transfer challenge: Hold let guard = notes.borrow_mut();, replace the later borrow() with try_borrow(), and handle the Err. Then call drop(guard) first and see the same call succeed.

Connections

  • Partial Moves: Move one field while borrowing another
  • Lifetime Elision: The common lifetime relationships Rust infers
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Interior Mutability (courseId "ownership", lessonId "interior-mutability-intro")
Link: https://crabrix.com/learn/ownership/interior-mutability-intro/
Goal: Cell and RefCell allow mutation behind an immutable outer binding.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=ownership/interior-mutability-intro) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.