From a1a8008aab6a1c70ed2a5ecde9d2f3ad21b689bf Mon Sep 17 00:00:00 2001 From: Jordan Gong Date: Mon, 21 Sep 2020 16:04:49 +0800 Subject: Use `Weak` to prevent reference cycles --- tree/src/main.rs | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 tree/src/main.rs (limited to 'tree/src/main.rs') diff --git a/tree/src/main.rs b/tree/src/main.rs new file mode 100644 index 0000000..2c9f238 --- /dev/null +++ b/tree/src/main.rs @@ -0,0 +1,55 @@ +use std::cell::RefCell; +use std::rc::{Rc, Weak}; + +#[derive(Debug)] +struct Node { + value: i32, + parent: RefCell>, + children: RefCell>>, +} + +fn main() { + let leaf = Rc::new(Node { + value: 3, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![]), + }); + + // println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); + + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); + + { + let branch = Rc::new(Node { + value: 5, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![Rc::clone(&leaf)]), + }); + + *leaf.parent.borrow_mut() = Rc::downgrade(&branch); + + println!( + "branch strong = {}, weak = {}", + Rc::strong_count(&branch), + Rc::weak_count(&branch), + ); + + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); + } + + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); + + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); +} -- cgit v1.2.3