I have a tree-like structure of owned elements and some parts of my code need to mutably access specific elements within that structure. A mutable reference to the root of the structure gets passed around to make this possible but accessing the exact elements that I need is inconvenient, here's a simplified example of what I'm talking about:
struct Node {
children: Vec<Node>,
}
struct Worker {
node_location: Vec<usize>,
}
impl Worker {
fn do_the_thing(&mut self, root: &mut Node) {
let mut node = root;
for idx in &self.node_location {
node = &mut node.children[*idx];
}
node.the_thing();
}
}
Now, the code above works and it does what I need it to do, but it has a number of problems, the worst one being that the tree structure changes over time and keeping all the indices up to date is super tricky.
What I would really like to do instead is something like this:
struct Node {
children: Vec<Rc<RefCell<Node>>>,
}
struct Worker {
node_location: Rc<RefCell<Node>>,
}
impl Worker {
fn do_the_thing(&mut self, root: &mut Node) {
let mude node = self.node_location.borrow_mut();
node.the_thing();
}
}
This also works, however, I now no longer have the guarantee that my child node is going to be available, anyone could have a reference to it now and my code could panic.
So basically I'm looking for some kind of reference that only becomes valid when combined with a &mut ref to the root of the tree, or something similar that would let me control who can access the elements of the tree and when.
Any ideas will be much appreciated!