Sub topic 15
Weak<T>: non-owning references that break cycles
This chapter assumes you know Rc<T>, RefCell<T>, and how Rc<RefCell<T>> lets several owners mutate shared data. It also assumes you have seen how a reference cycle keeps strong counts above zero, so the values are never freed.
What Weak does
A Weak<T> points to a value managed by an Rc<T> but does not own it. Two counts live in the shared allocation:
- The strong count is the number of
Rchandles. The value is dropped when it reaches 0. - The weak count is the number of
Weakhandles. It does not keep the value alive.
You create a Weak with Rc::downgrade(&rc), which returns a Weak<T> and raises the weak count by 1. To read through it, call upgrade(). This returns Option<Rc<T>>. You get Some while the value is alive and None once it has been dropped. Because the value may be gone, Rust forces you to handle both cases.
Parent and child without a cycle
In a tree, a parent owns its children, and each child only needs to find its parent. Make the downward link an Rc and the upward link a Weak. The upward link then adds no strong count, so no cycle can keep the nodes alive.
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Node {
value: i32,
parent: RefCell<Weak<Node>>,
children: RefCell<Vec<Rc<Node>>>,
}
fn main() {
let leaf = Rc::new(Node {
value: 3,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![]),
});
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.value));
let branch = Rc::new(Node {
value: 5,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![Rc::clone(&leaf)]),
});
*leaf.parent.borrow_mut() = Rc::downgrade(&branch);
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.value));
println!(
"branch strong = {}, weak = {}",
Rc::strong_count(&branch),
Rc::weak_count(&branch)
);
}The output is:
leaf parent = None
leaf parent = Some(5)
branch strong = 1, weak = 1Walking through it:
Weak::new()creates a handle that points to nothing, so the firstupgrade()returnsNone.Rc::clone(&leaf)puts a strong handle toleafinbranch.children.Rc::downgrade(&branch)stores a weak handle tobranchinleaf.parent. TheRefCelllets us replace it through a shared reference.branchhas one strong owner (the variable) and one weak handle (fromleaf).
When branch goes out of scope, its strong count drops to 0 and it is freed, even though leaf still holds a Weak to it. After that, leaf.parent.borrow().upgrade() returns None.
Common errors
- Calling methods on a
Weakdirectly. It has noDeref, so you mustupgrade()first. - Calling
unwrap()onupgrade()without being sure the owner is alive. If the owner is gone, the program panics. - Holding the upgraded
Rclonger than needed. The upgrade is a new strong handle, so it keeps the value alive until it is dropped. - Using
Weakfor the owning direction. If both links areWeak, nothing owns the nodes and they are freed immediately.
Exercise
In the example above, what does leaf.parent.borrow().upgrade() return after branch is dropped, and why?
Show answer
It returns None. Dropping branch takes its strong count to 0, so the value is freed. The Weak in leaf.parent does not keep it alive, so upgrade() finds no value to return.