Rc

    • If you need to mutate the data inside an , you will need to wrap the data in a type such as .
    • See Arc if you are in a multi-threaded context.
    • 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. struct Node {
    4. value: i64,
    5. parent: Option<Weak<RefCell<Node>>>,
    6. children: Vec<Rc<RefCell<Node>>>,
    7. }
    8. fn main() {
    9. let mut root = Rc::new(RefCell::new(Node {
    10. value: 42,
    11. }));
    12. let child = Rc::new(RefCell::new(Node {
    13. value: 43,
    14. children: vec![],
    15. parent: Some(Rc::downgrade(&root))
    16. }));
    17. root.borrow_mut().children.push(child);
    18. }