ownership
Rust Changing graph links with Weak
A child can record its parent after construction without becoming a strong owner of that parent. Keep strong edges in the intended ownership direction and weak edges for optional back-links. Strong cycles can prevent cleanup. Expected output (not executed): true false Why: The child does not keep the parent alive after its owner is dropped. Common mistake: Using strong pointers for every graph edge regardless of ownership.
Formal Syntax & Structure
rust syntaxrust
RefCell<Weak<Node>>Working Example
Example Snippetrust
use std::{cell::RefCell, rc::{Rc, Weak}};struct Node { parent: RefCell<Weak<Node>>, children: RefCell<Vec<Rc<Node>>> }fn node() -> Rc<Node> { Rc::new(Node { parent: RefCell::new(Weak::new()), children: RefCell::new(Vec::new()) }) }fn main() { let child = node(); { let parent = node(); *child.parent.borrow_mut() = Rc::downgrade(&parent); parent.children.borrow_mut().push(Rc::clone(&child)); println!("{}", child.parent.borrow().upgrade().is_some()); } println!("{}", child.parent.borrow().upgrade().is_some());}