How do I express mutually recursive structures in Rust? explains how to represent graph-like structures but it does not explain how to walk the graph (only to add more children). The Rc<RefCell<T>>
solution I tried to adapt did not compile.
I am looking for a way to design and walk a graph-like structure in safe Rust, utilizing Rc<T>
and/or RefCell<T>
for interior mutability. My current Node
does not compile because of &mut T
aliasing rules:
struct Node {
parent: Option<&mut Node>, // a mutable reference to the Node's owner
children: Vec<Node>, // each Node owns its children
}
impl Node {
fn add_child(&mut self, x: Node) {
self.children.push(x);
}
fn get_child(&mut self, i: usize) -> &mut Node {
&mut self.children[i]
}
fn get_parent(&mut self) -> &mut Node {
self.parent.expect("No parent!")
}
}
Example functionality:
let mut top_node = Node::new(None);
let mut ptr = &mut top_node;
ptr.add_child(Node::new(&mut ptr)); // add a child to top_node
ptr = ptr.get_child(0); // walk down to top_node's 0th child.
ptr = ptr.get_parent(); // walk back up to top_node
I repeatedly rewrote this implementation replacing &mut T
with combinations of Rc
, Weak
, RefCell
, and RefMut
to no avail. I don't understand enough about the underlying memory management.
Could someone with more experience using interior mutability explain how to correctly design and walk this graph?