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;
  2. fn main() {
  3. let mut a = Rc::new(10);
  4. let mut b = a.clone();
  5. println!("a: {a}");
  6. println!("b: {b}");
  7. }
  • 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.

  • clone is cheap: creates a pointer to the same allocation and increases the reference count.
  • make_mut actually clones the inner value if necessary (“clone-on-write”) and returns a mutable reference.
  • You can downgrade() a Rc into a weakly reference-counted object to create cycles that will be dropped properly (likely in combination with RefCell).
  1. use std::rc::{Rc, Weak};
  2. use std::cell::RefCell;
  3. #[derive(Debug)]
  4. struct Node {
  5. value: i64,
  6. parent: Option<Weak<RefCell<Node>>>,
  7. children: Vec<Rc<RefCell<Node>>>,
  8. }
  9. fn main() {
  10. let mut root = Rc::new(RefCell::new(Node {
  11. value: 42,
  12. parent: None,
  13. children: vec![],
  14. }));
  15. let child = Rc::new(RefCell::new(Node {
  16. value: 43,
  17. children: vec![],
  18. parent: Some(Rc::downgrade(&root))
  19. }));
  20. root.borrow_mut().children.push(child);
  21. println!("graph: {root:#?}");
  22. }