liveBook · Manning

Refcell

As explained in Learn Rust in a Month of Lunches

RefCell is a Rust standard-library container that enforces borrowing rules at run time and permits mutation through an immutable access path.

RefCell is a Rust standard-library container for interior mutability: it lets code change a value through an otherwise immutable access path. It resembles regular references, but checks borrowing rules at run time instead of compilation time. section 10.3.2 section 10.3

Use the borrowing methods as follows:

  • Call borrow() for immutable access; multiple immutable borrows are allowed. section 10.3.2
  • Call borrow_mut() for mutable access; one mutable borrow is allowed, but it cannot coexist with immutable borrows. section 10.3.2
  • Use try_borrow_mut() when a second mutable borrow might occur; it returns an error instead of panicking. section 10.3.2 section 10.4
  • Keep RefCell out of multithreaded code; unlike Mutex and RwLock, it does not provide the guards needed for shared-thread mutation. section 10.3.2 section 10.4

Mutating a field through an immutable user

A User can store active: RefCell<bool> and initialize it with RefCell::new(true). Mutation can then happen with *user_1.active.borrow_mut() = false, even when user_1 itself was not declared mutable. Holding one mutable borrow and requesting another compiles, but running the program immediately panics with BorrowMutError. section 10.3.2

use std::cell::RefCell;
 
#[derive(Debug)]
struct User {
    id: u32,
    year_registered: u32,
    username: String,
    active: RefCell<bool>,     #1
}
 
fn main() {
    let user_1 = User {
        id: 1,
        year_registered: 2020,
        username: "User 1".to_string(),
        active: RefCell::new(true),
    };
 
    println!("{:?}", user_1.active);
}

Inspect the minimal User definition and RefCell::new initialization before adding mutable borrows. section 10.3.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains initialization, borrowing methods, runtime panics, error-returning alternatives, and thread restrictions.
Examples
Uses a User with an active RefCell<bool>, direct mutation, double mutable borrowing, and the resulting panic.
What it assumes
Assumes basic immutable and mutable borrowing while teaching interior mutability and runtime borrow checking.
What you can do after
Apply it via RefCell::new, borrow, borrow_mut, and try_borrow_mut while avoiding invalid simultaneous borrows.
How it connects
Connects interior mutability with borrowing, Cell, Mutex, RwLock, and multithreading.

Also explained in

Compare how 3 books explain refcell →

Related concepts

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