liveBook · Manning

Interior mutability

As explained in Rust in Action: Systems programming concepts and techniques

Interior mutability is a design property allowing a value's internal state to change through an otherwise immutable interface.

Interior mutability lets a Rust type appear immutable while its internal state changes. An Rc<T> or Arc<T>, for example, changes its reference count as references are made and expire, even though it presents an immutable façade. section 3.4.1

This helps when an interface accepts an immutable value but the value still needs to change. Cell<T> can wrap an owned value; RefCell<T> can wrap a value accessed through references. These options add runtime cost. section 6.2.2

Combining shared ownership and interior mutability

A type such as Rc<RefCell<T>> combines reference-counted shared ownership with interior mutability. It offers more flexibility, but the two mechanisms each carry a runtime cost. section 6.2.2

The distinction also explains why let and const are not interchangeable: data behind a let binding can change. Ordinary borrowing still matters—read-only borrows can alias, while a read-write borrow must not alias other access. section 3.4.1 section 4.6

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Defines the property and compares wrapper choices and runtime costs, without detailing their implementations.
Examples
Illustrates changing Rc<T> and Arc<T> reference counts and the composed type Rc<RefCell<T>>.
What it assumes
Builds on let bindings, read-only and read-write borrows, and reference-counted ownership.
What you can do after
Apply it via Cell<T> or RefCell<T> when an immutable interface must accommodate changing state, while accounting for runtime cost.
How it connects
Connects interior mutability to borrowing, aliasing, reference counting, and shared ownership.

Also explained in

Compare how 3 books explain interior mutability →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.