Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. use std::cell::RefCell;
  2. use std::rc::{Rc, Weak};
  3.  
  4. #[derive(Debug)]
  5. struct Node {
  6. value: i32,
  7. parent: RefCell<Weak<Node>>,
  8. children: RefCell<Vec<Rc<Node>>>,
  9. }
  10. fn main() {
  11. let root = Rc::new(Node {
  12. value: 0,
  13. parent: RefCell::new(Weak::new()),
  14. children: RefCell::new(vec![]),
  15. });
  16.  
  17. let leaf = Rc::new(Node {
  18. value: 3,
  19. parent: RefCell::new(Weak::new()),
  20. children: RefCell::new(vec![]),
  21. });
  22. println!(
  23. "leaf strong = {}, weak = {}",
  24. Rc::strong_count(&leaf),
  25. Rc::weak_count(&leaf),
  26. );
  27. println!(
  28. "root strong = {}, weak = {}",
  29. Rc::strong_count(&root),
  30. Rc::weak_count(&root),
  31. );
  32. println!("-------------------------------");
  33. {
  34. let branch = Rc::new(Node {
  35. value: 10,
  36. parent: RefCell::new(Rc::downgrade(&root)),
  37. children: RefCell::new(vec![Rc::clone(&leaf)]),
  38. });
  39. *leaf.parent.borrow_mut() = Rc::downgrade(&branch);
  40. root.children.borrow_mut().push(Rc::clone(&branch));
  41. println!(
  42. "root strong = {}, weak = {}",
  43. Rc::strong_count(&root),
  44. Rc::weak_count(&root),
  45. );
  46. println!(
  47. "branch strong = {}, weak = {}",
  48. Rc::strong_count(&branch),
  49. Rc::weak_count(&branch),
  50. );
  51. println!(
  52. "leaf strong = {}, weak = {}",
  53. Rc::strong_count(&leaf),
  54. Rc::weak_count(&leaf),
  55. );
  56. println!("-------------------------------");
  57. }
  58. println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
  59. println!(
  60. "leaf strong = {}, weak = {}",
  61. Rc::strong_count(&leaf),
  62. Rc::weak_count(&leaf),
  63. );
  64. println!(
  65. "root strong = {}, weak = {}",
  66. Rc::strong_count(&root),
  67. Rc::weak_count(&root),
  68. );
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement