Skip to content

Commit 7bd5e30

Browse files
committed
weakrefs
1 parent e1629a5 commit 7bd5e30

2 files changed

Lines changed: 60 additions & 2 deletions

File tree

course/src/main.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,5 @@ fn main() {
1313
//stuff::error_handling();
1414
//guessgame::guess_game();
1515
intmut::intmut();
16+
intmut::weakrefs();
1617
}

intmut/src/lib.rs

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
use std::{cell::RefCell, rc::Rc};
21
use List::{Cons, Nil};
2+
use std::cell::RefCell;
3+
use std::rc::{Rc, Weak};
34

45
#[derive(Debug)]
56
enum 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

Comments
 (0)