|
| 1 | +/// for illustration purposes only, do not use IRL! |
| 2 | +use std::cell::RefCell; // a "runtime borrow-checker" |
| 3 | +use std::fmt::Debug; |
| 4 | +use std::rc::{Rc, Weak}; |
| 5 | + |
| 6 | +#[derive(Debug)] |
| 7 | +struct Node<T> { |
| 8 | + parent: Option<Weak<RefCell<Node<T>>>>, |
| 9 | + left: Option<Rc<RefCell<Node<T>>>>, |
| 10 | + right: Option<Rc<RefCell<Node<T>>>>, |
| 11 | + value: T, |
| 12 | +} |
| 13 | + |
| 14 | +impl<T: Debug> Node<T> { |
| 15 | + fn new(value: T) -> Node<T> { |
| 16 | + Node { |
| 17 | + parent: None, |
| 18 | + left: None, |
| 19 | + right: None, |
| 20 | + value, |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + fn print_parent(&self) { |
| 25 | + if let Some(parent) = &self.parent { |
| 26 | + if let Some(parent) = parent.upgrade() { |
| 27 | + println!("Parent: {:?}", parent.borrow().value); |
| 28 | + } else { |
| 29 | + println!("Parent: no more parent"); |
| 30 | + } |
| 31 | + } else { |
| 32 | + println!("Parent: None"); |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +fn main() { |
| 38 | + let root = Rc::new(RefCell::new(Node::new(0))); |
| 39 | + let node = Rc::new(RefCell::new(Node::new(1))); |
| 40 | + node.borrow_mut().parent = Some(Rc::downgrade(&root)); |
| 41 | + |
| 42 | + let node2 = Rc::new(RefCell::new(Node::new(2))); |
| 43 | + |
| 44 | + root.borrow_mut().parent = Some(Rc::downgrade(&node2)); |
| 45 | + root.borrow_mut().left = Some(node); |
| 46 | + |
| 47 | + println!("Root: {:?}", *root.borrow()); |
| 48 | + if let Some(left) = &root.borrow().left { |
| 49 | + &left.borrow().print_parent(); |
| 50 | + }; |
| 51 | + &root.borrow().print_parent(); |
| 52 | + drop(node2); |
| 53 | + &root.borrow().print_parent(); |
| 54 | +} |
0 commit comments