Ownership in Practice · 18 min · free with an account

Interior Mutability

Lesson preview · about 30%

Move a checked borrow rule to runtime.

Core idea

Cell and RefCell allow mutation behind an immutable outer binding.

Start with the idea

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 learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Ownership Mastery