How to Use Rc<RefCell<T>> for Shared Mutable State

Use Rc<RefCell<T>> to share mutable state across multiple owners by combining reference counting with runtime borrow checking.

Combine Rc<T> for shared ownership with RefCell<T> for interior mutability to modify data through shared references at runtime. Wrap your data in RefCell, place that inside Rc, and clone the Rc to share it; then call .borrow_mut() to mutate the inner value.

use std::rc::Rc;
use std::cell::RefCell;

fn main() {
    let value = Rc::new(RefCell::new(5));
    let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil)));
    let b = Cons(Rc::new(RefCell::new(3)), Rc::clone(&a));
    let c = Cons(Rc::new(RefCell::new(4)), Rc::clone(&a));

    *value.borrow_mut() += 10;

    println!("a after = {:?}", a);
    println!("b after = {:?}", b);
    println!("c after = {:?}", c);
}

#[derive(Debug)]
enum List {
    Cons(Rc<RefCell<i32>>, Rc<List>),
    Nil,
}

use List::{Cons, Nil};