RefCell<T> checks Rust's borrow rules while the program runs, allowing mutation through a shared owner when the borrowing pattern is valid.

Program

Play the program to choose a log item and push it into a vector stored inside RefCell.

item
refcell_buffer.rs
Replay: real traced execution (multi-file project)
use std::cell::RefCell;

fn main() {
    let item = "beta";
    let log = RefCell::new(Vec::new());
    log.borrow_mut().push("start");
    log.borrow_mut().push(item);
    let count = log.borrow().len();
    println!("{count}");
}
use std::cell::RefCell;

fn main() {
    let item = "alpha";
    let log = RefCell::new(Vec::new());
    log.borrow_mut().push("start");
    log.borrow_mut().push(item);
    let count = log.borrow().len();
    println!("{count}");
}
use std::cell::RefCell;

fn main() {
    let item = "gamma";
    let log = RefCell::new(Vec::new());
    log.borrow_mut().push("start");
    log.borrow_mut().push(item);
    let count = log.borrow().len();
    println!("{count}");
}
  1. item ← "beta", log ← RefCell { value: [] }, count ← 2

    3fn main() {4    let ite→ "beta"m = "beta"; //@item="beta", "alpha", "gamma"5    let lo→ RefCell { value: [] }g = RefCell::new(Vec::new());6    log.borrow_mut().push("start");7    log.borrow_mut().push(item);8    let coun→ 2t = log.borrow().len();9    println!("{count}");10}
    output2
  1. item ← "alpha", log ← RefCell { value: [] }, count ← 2

    3fn main() {4    let ite→ "alpha"m = "alpha";5    let lo→ RefCell { value: [] }g = RefCell::new(Vec::new());6    log.borrow_mut().push("start");7    log.borrow_mut().push(item);8    let coun→ 2t = log.borrow().len();9    println!("{count}");10}
    output2
  1. item ← "gamma", log ← RefCell { value: [] }, count ← 2

    3fn main() {4    let ite→ "gamma"m = "gamma";5    let lo→ RefCell { value: [] }g = RefCell::new(Vec::new());6    log.borrow_mut().push("start");7    log.borrow_mut().push(item);8    let coun→ 2t = log.borrow().len();9    println!("{count}");10}
    output2
RefCell<T> `RefCell<T>` moves borrow checking for the wrapped value to runtime.
borrow_mut `borrow_mut` grants a temporary mutable borrow when no conflicting borrow exists.
borrow `borrow` grants a temporary shared borrow for reading.