Rc
Rc is a reference-counted shared pointer. Use this when you need to refer to the same data from multiple places:
1. use std::rc::Rc;
3. fn main() {
4. let mut a = Rc::new(10);
5. let mut b = a.clone();
7. println!("a: {a}");
8. println!("b: {b}");
9. }
- If you need to mutate the data inside an
Rc, you will need to wrap the data in a type such as Cell or RefCell. - See Arc if you are in a multi-threaded context.
- You can downgrade a shared pointer into a Weak pointer to create cycles that will get dropped.
- Like C++’s
std::shared_ptr. cloneis cheap: creates a pointer to the same allocation and increases the reference count.make_mutactually clones the inner value if necessary (“clone-on-write”) and returns a mutable reference.- You can
downgrade()aRcinto a weakly reference-counted object to create cycles that will be dropped properly (likely in combination withRefCell).
1. use std::rc::{Rc, Weak};
2. use std::cell::RefCell;
4. #[derive(Debug)]
5. struct Node {
6. value: i64,
7. parent: Option<Weak<RefCell<Node>>>,
8. children: Vec<Rc<RefCell<Node>>>,
9. }
11. fn main() {
12. let mut root = Rc::new(RefCell::new(Node {
13. value: 42,
14. parent: None,
15. children: vec![],
16. }));
17. let child = Rc::new(RefCell::new(Node {
18. value: 43,
19. children: vec![],
20. parent: Some(Rc::downgrade(&root))
21. }));
22. root.borrow_mut().children.push(child);
24. println!("graph: {root:#?}");
25. }
