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 46 47 48 49 50 51
| use std::rc::Rc; use std::cell:RefCell; use crate::List::{Cons,Nil}; use std::rc::Weak;
enum List { Cons(i32,RefCell<Weak<List>>), Nil, } impl List { fn tail(&self) -> Option<&RefCell<Weak<List>>> { match self { Cons(_,item) => Some(item), Nil => None, } } } fn main() { let a = Rc::new(Cons(5,RefCell::new(Weak::new())));
println!("1,a strong count = {},weak count = {}",Rc::strong_count(&a),Rc::weak_count(&a)); println!("1 a.tail = {:?}",a.tail());
let b = Rc::new(Cons(10,RefCell::new(Weak::new()))); if let Some(link) = b.tail() { *link.borrow_mut() = Rc::downgrade(&a); } println!("2,a strong count = {},weak count = {}",Rc::strong_count(&a),Rc::weak_count(&a)); println!("2,b strong count = {},weak count = {}",Rc::strong_count(&b),Rc::weak_count(&b)); println!("2 b.tail = {:?}",b.tail());
if let Some(link) = a.tail() { *link.borrow_mut = Rc::downgrade(&b); } println!("3,a strong count = {},weak count = {}",Rc::strong_count(&a),Rc::weak_count(&a)); println!("3,b strong count = {},weak count = {}",Rc::strong_count(&b),Rc::weak_count(&b)); println!("3 b.tail = {:?}",a.tail());
}
|