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!(¬_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


