Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ MEMORY & SHARED OWNERSHIP
BUILD NOTE 39 / 53

Share locally, check carefully.

Separate shared ownership from runtime-checked mutation.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

Rc<T> provides reference-counted shared ownership within one thread. RefCell<T> allows interior mutation by checking borrowing rules at runtime: many shared borrows or one exclusive borrow. Violations panic with borrow or can return an error with try_borrow. Rc does not make data thread-safe, and reference cycles can prevent cleanup; Weak references help represent non-owning back-links. Prefer simple ownership first, then introduce these tools when the graph of owners genuinely requires them.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/rc-refcell/src/main.rs
use std::{cell::RefCell, rc::Rc};
fn main() {
    let shared = Rc::new(RefCell::new(vec!["plan"]));
    let other = Rc::clone(&shared);
    other.borrow_mut().push("build");
    println!("{:?}", shared.borrow());
    println!("owners={}", Rc::strong_count(&shared));
}
↳ EXPECTED OUTPUT
["plan", "build"]
owners=2
  1. 1

    Rc::clone shares the allocation rather than copying the vector.

  2. 2

    The temporary mutable borrow ends after push.

  3. 3

    The later shared borrow sees the update.

From the extracted rust-workbench folder
cargo run -p lesson_rc_refcell

03 Mind the boundary

04 Your next build

A SMALL MISSION

Hold a shared borrow and confirm try_borrow_mut fails, then succeeds after the shared guard is dropped.

Reveal one possible solution +
solutions/rc-refcell/src/main.rs
use std::cell::RefCell;
fn main() {
    let cell = RefCell::new(1);
    let guard = cell.borrow();
    assert!(cell.try_borrow_mut().is_err());
    drop(guard);
    *cell.try_borrow_mut().unwrap() = 2;
    assert_eq!(*cell.borrow(), 2);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Can Rc by itself be sent safely between threads?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.