liveBook · Manning

Cell

As explained in Code Like a Pro in Rust

Cell is a Rust standard-library type that provides interior mutability by replacing or retrieving values without exposing references to its contents.

Cell provides interior mutability: it lets code change data inside an otherwise immutable structure by moving values in and out, rather than exposing references to its contents. It is a safe escape hatch when ordinary mutable borrowing is too restrictive. section 5.6

Choose the interior-mutability tool to match the access pattern:

  • Use Cell when moving values in and out is suitable. Prefer RefCell when you need to borrow references to the stored data. section 5.6
  • Use either sparingly. If it mainly serves to get around the borrow checker, reconsider the data structure. section 5.6
  • For access across threads, use synchronization such as Mutex or RwLock, typically with Arc. section 5.6

When Cell is not the fit

A doubly linked list with shared node ownership uses Rc<RefCell<ListItem<T>>>. Its nodes need mutable access through shared pointers, so the implementation uses RefCell’s reference-borrowing behavior rather than Cell’s value movement. section 5.6

How Code Like a Pro in Rust covers it

How deep it goes
Explains Cell through its value-movement trade-off with RefCell, but does not work through a Cell implementation.
Examples
Uses an Rc<RefCell<ListItem<T>>> doubly linked list to illustrate the reference-borrowing alternative; provides no Cell-specific example.
What it assumes
Assumes familiarity with Rust’s mutable references and borrow checker while introducing interior mutability as an escape hatch.
What you can do after
Evaluate/understand when Cell’s value movement fits and when reference borrowing or cross-thread synchronization calls for another type.
How it connects
Connects Cell to interior mutability, the borrow checker, RefCell, Rc, Arc, Mutex, and RwLock.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.