Weak References Break Rc Ownership Cycles
Give a child a Weak back-reference instead of a strong Rc so parent-child loops never leak: downgrade stores it, upgrade returns Option when the parent lives.
Code
use std::cell::RefCell;
use std::rc::{Rc, Weak};
// 树结构惯例:父强引用子,子用 Weak 回指父,避免强引用成环
#[derive(Debug)]
struct Node {
name: String,
children: RefCell<Vec<Rc<Node>>>,
parent: RefCell<Weak<Node>>,
}
impl Node {
fn new(name: &str) -> Rc<Node> {
Rc::new(Node {
name: name.into(),
children: RefCell::new(Vec::new()),
parent: RefCell::new(Weak::new()),
})
}
}
fn main() {
let root = Node::new("root");
let leaf = Node::new("leaf");
// 强引用:父持有子
root.children.borrow_mut().push(Rc::clone(&leaf));
// 弱引用:子只记一个 downgrade 出来的 Weak
*leaf.parent.borrow_mut() = Rc::downgrade(&root);
// upgrade 返回 Option<Rc>:父还活着就拿到 Some
if let Some(parent) = leaf.parent.borrow().upgrade() {
println!("{} -> {}", leaf.name, parent.name);
}
println!(
"leaf strong {} weak {}, root strong {} weak {}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf),
Rc::strong_count(&root),
Rc::weak_count(&root)
);
// 循环不会泄漏:drop root 后,leaf 里的 Weak upgrade 返回 None
drop(root);
println!("root gone, parent upgrade: {}", leaf.parent.borrow().upgrade().is_none());
}How it works
Count the functions new and main as the entire surface area of Weak References Break Rc Ownership Cycles.
Using it
Entry signature: fn new(name: &str) -> Rc<Node>
The demo output is labeled (leaf strong, root gone, parent upgrade:), so every printed line maps back to its originating operation.
Treat main as the orchestrator calling new in a fixed order.
Key statements
if let Some(parent) = leaf.parent.borrow().upgrade() {
println!("{} -> {}", leaf.name, parent.name);
}
fn new(name: &str) -> Rc<Node> {
Rc::new(Node {
name: name.into(),
children: RefCell::new(Vec::new()),
parent: RefCell::new(Weak::new()),
})
}
Interactive Tools for This Topic
FAQ
- What does Weak References Break Rc Ownership Cycles print when run?
- Execute the whole file; each printed line is prefixed with a label like `leaf strong`, `root gone, parent upgrade:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.