liveBook · Manning

Refcell

As explained in Idiomatic Rust

RefCell is Rust's single-threaded interior-mutability container that checks borrowing rules at runtime.

Rust normally makes data inside an immutable binding immutable too. RefCell is an interior-mutability container: it lets you mutate an owned value without making the container binding mutable. Unlike ordinary inherited mutability, this access is checked at runtime. section 9.4 section 9.5

Mutate an owned String

An immutable String cannot call push_str directly. Move it into a RefCell with `let value = RefCell::from(immutable_string);`, then call `value.borrow_mut().push_str("... or can it?");`. The binding `value` remains immutable, but the contained string changes. section 9.5

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 listing shows the failed direct mutation beside the RefCell::from and borrow_mut() alternative. section 9.5

Use RefCell when interior mutability serves a real ownership need, not simply to avoid thinking through borrowing. It does not provide shared ownership: Rc and Arc serve that separate purpose. Cell is another interior-mutability option, but changes its value by replacement rather than direct mutable access. section 9.4 section 10.8

How Idiomatic Rust covers it

How deep it goes
Explains runtime-enforced interior mutability and demonstrates borrow_mut(), without detailing borrow-conflict behavior.
Examples
Moves an immutable String into RefCell, calls borrow_mut().push_str(...), and displays the changed value.
What it assumes
Assumes familiarity with Rust bindings, ownership, and borrowing; contrasts their usual restrictions with interior mutability.
What you can do after
Apply it via RefCell::from and borrow_mut() to mutate an owned String without a mutable container binding.
How it connects
Connects inherited mutability, Cell, OnceCell, borrowing, Rc, and Arc through the distinction between mutation and shared ownership.

Also explained in

Compare how 3 books explain refcell →

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.