1- use std:: { cell:: RefCell , rc:: Rc } ;
21use List :: { Cons , Nil } ;
2+ use std:: cell:: RefCell ;
3+ use std:: rc:: { Rc , Weak } ;
34
45#[ derive( Debug ) ]
56enum List {
@@ -98,4 +99,60 @@ mod tests {
9899
99100 assert_eq ! ( mock_messenger. sent_messages. borrow( ) . len( ) , 1 ) ;
100101 }
101- }
102+ }
103+
104+ // ******************
105+
106+ #[ derive( Debug ) ]
107+ struct Node {
108+ value : i32 ,
109+ parent : RefCell < Weak < Node > > ,
110+ children : RefCell < Vec < Rc < Node > > > ,
111+ }
112+
113+ pub fn weakrefs ( ) {
114+ let leaf = Rc :: new ( Node {
115+ value : 3 ,
116+ parent : RefCell :: new ( Weak :: new ( ) ) ,
117+ children : RefCell :: new ( vec ! [ ] ) ,
118+ } ) ;
119+ {
120+ let c = leaf. children . borrow ( ) ;
121+ println ! ( "leaf: ({}, {c:?})" , leaf. value) ;
122+ }
123+
124+ println ! (
125+ "leaf strong = {}, weak = {}" ,
126+ Rc :: strong_count( & leaf) ,
127+ Rc :: weak_count( & leaf) ,
128+ ) ;
129+
130+ {
131+ let branch = Rc :: new ( Node {
132+ value : 5 ,
133+ parent : RefCell :: new ( Weak :: new ( ) ) ,
134+ children : RefCell :: new ( vec ! [ Rc :: clone( & leaf) ] ) ,
135+ } ) ;
136+
137+ * leaf. parent . borrow_mut ( ) = Rc :: downgrade ( & branch) ;
138+
139+ println ! (
140+ "branch strong = {}, weak = {}" ,
141+ Rc :: strong_count( & branch) ,
142+ Rc :: weak_count( & branch) ,
143+ ) ;
144+
145+ println ! (
146+ "leaf strong = {}, weak = {}" ,
147+ Rc :: strong_count( & leaf) ,
148+ Rc :: weak_count( & leaf) ,
149+ ) ;
150+ }
151+
152+ println ! ( "leaf parent = {:?}" , leaf. parent. borrow( ) . upgrade( ) ) ;
153+ println ! (
154+ "leaf strong = {}, weak = {}" ,
155+ Rc :: strong_count( & leaf) ,
156+ Rc :: weak_count( & leaf) ,
157+ ) ;
158+ }
0 commit comments