1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| 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, parent: RefCell::new(Weak::new()); children:: RefCell::new(Vec![]), }); 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)]),
}}; println!( "branch strong = {},weak = {}", Rc::strong_count(&branch), Rc::weak_count(&branch)); *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) );
}
|