liveBook · Manning

Interior mutability

As explained in Idiomatic Rust

Interior mutability is a capability that permits mutation through an otherwise shared reference while enforcing access rules through a runtime or specialized checking mechanism.

Rust normally makes data inside an immutable value immutable too. Interior mutability lets a Cell, RefCell, or OnceCell offer mutation through an otherwise immutable container, with access rules enforced at runtime rather than by the compiler. section 9.4

Choose a container based on how it permits access:

  • Cell permits replacing its value, not directly mutating the value inside. section 9.4
  • RefCell and OnceCell can provide a mutable reference to their data. section 9.4
  • These containers allow hidden mutability, so weigh that tradeoff against the flexibility they provide. section 9.4
Listing 9.3 Using RefCell for interior mutability
let immutable_string =                              #1
  String::from("This string cannot be changed");   
// immutable_string.push_str("... or can it?"); // error: cannot borrow
`immutable_string` as mutable, as it is not declared as mutable       #2
dbg!(&immutable_string);

let not_so_immutable_string = RefCell::from(immutable_string);    #3
not_so_immutable_string
    .borrow_mut()
    .push_str("... or can it?");    #4
dbg!(&not_so_immutable_string);

The example moves a String into a RefCell, then uses borrow_mut to append text despite the original binding being immutable. section 9.5

How Idiomatic Rust covers it

How deep it goes
Defines runtime enforcement and contrasts Cell replacement with mutable access through RefCell and OnceCell.
Examples
Demonstrates appending to a String through RefCell::borrow_mut after moving the string into the container.
What it assumes
Assumes familiarity with Rust bindings and inherited mutability, contrasting them with runtime-enforced mutation.
What you can do after
Apply interior mutability with RefCell to modify owned data behind an immutable binding.
How it connects
Connects Rust mutability and inherited mutability with Cell, RefCell, and OnceCell.

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 Idiomatic Rust. The section links point to the parts of the book it draws on.