Cleanup follows ownership.
Release resources predictably and avoid strong-reference cycles.
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.
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());
}alive=true alive=false
- 1
downgrade creates a non-owning weak handle.
- 2
The first upgrade temporarily creates a strong owner.
- 3
After the final strong owner drops, upgrade returns None.
cargo run -p lesson_drop_weak03 Mind the boundary
04 Your next build
Implement Drop for a simple guard and use an Rc<RefCell<Vec<_>>> log to check cleanup happened.
Reveal one possible solution +
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
Does a Weak reference keep the value alive?
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.