- 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
).
use std::rc::{Rc, Weak};
use std::cell::RefCell;
struct Node {
value: i64,
parent: Option<Weak<RefCell<Node>>>,
children: Vec<Rc<RefCell<Node>>>,
}
fn main() {
let mut root = Rc::new(RefCell::new(Node {
value: 42,
}));
let child = Rc::new(RefCell::new(Node {
value: 43,
children: vec![],
parent: Some(Rc::downgrade(&root))
}));
root.borrow_mut().children.push(child);
}