ownership
Rust Ownership graphs and weak parent links
A child can remember its parent without owning it. In a graph where the parent owns children, weak back-links avoid a strong ownership cycle. A cycle of strong handles can retain values forever; memory safety is not a guarantee against leaks. This example isolates the back-link without requiring interior mutability. Expected output (not executed): root true Why: The weak backlink lets the child outlive the parent without keeping the parent alive. Common mistake: Making every edge in a bidirectional graph a strong Rc.
Formal Syntax & Structure
rust syntaxrust
struct Child { parent: Weak<Parent> }Working Example
Example Snippetrust
use std::rc::{Rc, Weak};struct Parent { name: String }struct Child { parent: Weak<Parent> }fn main() { let parent = Rc::new(Parent { name: "root".into() }); let child = Child { parent: Rc::downgrade(&parent) }; if let Some(p) = child.parent.upgrade() { println!("{}", p.name); } drop(parent); println!("{}", child.parent.upgrade().is_none());}