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

Cleanup follows ownership.

Release resources predictably and avoid strong-reference cycles.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

RAII ties resource cleanup to ownership: file handles, locks, and heap allocations are released as their owners are dropped. The Drop trait customizes cleanup, but you should keep it dependable and avoid panicking. std::mem::drop ends ownership early. Weak<T> points at a reference-counted allocation without keeping its value alive; upgrade returns Option because the value may already be gone. Weak is useful for parent links and registries where observation should not imply ownership.

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/drop-weak/src/main.rs
use std::rc::Rc;
fn main() {
    let owner = Rc::new(String::from("session"));
    let observer = Rc::downgrade(&owner);
    println!("alive={}", observer.upgrade().is_some());
    drop(owner);
    println!("alive={}", observer.upgrade().is_some());
}
↳ EXPECTED OUTPUT
alive=true
alive=false
  1. 1

    downgrade creates a non-owning weak handle.

  2. 2

    The first upgrade temporarily creates a strong owner.

  3. 3

    After the final strong owner drops, upgrade returns None.

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

03 Mind the boundary

04 Your next build

A SMALL MISSION

Implement Drop for a simple guard and use an Rc<RefCell<Vec<_>>> log to check cleanup happened.

Reveal one possible solution +
solutions/drop-weak/src/main.rs
use std::{cell::RefCell, rc::Rc};
struct Guard(Rc<RefCell<Vec<&'static str>>>);
impl Drop for Guard {
    fn drop(&mut self) {
        self.0.borrow_mut().push("closed");
    }
}
fn main() {
    let log = Rc::new(RefCell::new(Vec::new()));
    {
        let _guard = Guard(Rc::clone(&log));
    }
    assert_eq!(*log.borrow(), ["closed"]);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Does a Weak reference keep the value alive?

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.