Enabling Multiple Owners with Rc<T> and Preventing Cycles with Weak<T>
Owner: SnippetBot
Created: 2026-09-10 00:00:22
Size: 1.62 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use std::rc::{Rc, Weak};
use std::cell::RefCell;
// Define a Node for a graph-like structure
#[derive(Debug)]
struct Node {
value: i32,
// Using Rc for shared ownership of children
children: RefCell<Vec<Rc<Node>>>,
// Using Weak to create a parent link without forming a reference cycle
parent: RefCell<Weak<Node>>,
}
impl Node {
fn new(value: i32) -> Rc<Self> {
Rc::new(Node {
value,
children: RefCell::new(vec![]),
parent: RefCell::new(Weak::new()),
})
}
fn add_child(self: &Rc<Self>, child: Rc<Node>) {
child.parent.borrow_mut().replace(Rc::downgrade(self));
self.children.borrow_mut().push(child);
}
}
fn main() {
let root = Node::new(1);
let child1 = Node::new(2);
let child2 = Node::new(3);
// Establish parent-child relationships
root.add_child(Rc::clone(&child1));
root.add_child(Rc::clone(&child2));
println!("Root ref count: {}", Rc::strong_count(&root)); // Should be 1 (root) + 2 (child parent links if not weak)
println!("Child1 parent weak ref count: {}", Weak::strong_count(&child1.parent.borrow())); // Should be 1
// Demonstrates that even if child1 is dropped, root can still exist
// If parent was Rc, this would create a cycle and memory leak.
drop(child1);
println!("Root after child1 drop: {:#?}", root);
// Note: Rc::strong_count(&root) might not immediately reflect internal child drops
// as the Rc for the children still exists within root's children vector.
// The key is that the *parent link* from child to root doesn't prevent root from being dropped.
}