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>>, // Using Weak to create a parent link without forming a reference cycle parent: RefCell>, } impl Node { fn new(value: i32) -> Rc { Rc::new(Node { value, children: RefCell::new(vec![]), parent: RefCell::new(Weak::new()), }) } fn add_child(self: &Rc, child: Rc) { 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. }