Created
July 12, 2018 15:53
-
-
Save rust-play/3096c5b606b05e0fc06b8de85f422292 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::rc::{Rc,Weak}; | |
use std::cell::RefCell; | |
#[derive(Debug)] | |
struct Node { | |
value: i32, | |
parent: RefCell<Weak<Node>>, | |
children: RefCell<Vec<Rc<Node>>>, | |
} | |
fn main() { | |
let leaf = Rc::new(Node { | |
value: 3, | |
children: RefCell::new(vec![]), | |
parent: RefCell::new(Weak::new()), | |
}); | |
println!( | |
"leaf strong = {} weak = {}", | |
Rc::strong_count(&leaf), | |
Rc::weak_count(&leaf) | |
); | |
{ | |
let branch = Rc::new(Node{ | |
value:5, | |
children: RefCell::new(vec![Rc::clone(&leaf)]), | |
parent: RefCell::new(Weak::new()), | |
}); | |
*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), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment