I am trying to build a path from the root to leaf nodes in a tree-like data structure. The path is represented by an array (path
) of mutable references to nodes:
fn build_path(&mut self, index: Index, shift: Shift) {
debug_assert!(shift.0 >= BITS_PER_LEVEL);
let mut path: [Option<&mut Node<T>>; MAX_HEIGHT] = new_path!();
let mut path_i = 0;
let mut node = self;
let mut shift = shift;
while shift.0 != BITS_PER_LEVEL {
let cnode = node;
let child = match *cnode {
Node::Leaf { .. } => unreachable!(),
Node::RelaxedBranch { .. } => unreachable!(),
Node::Branch { ref mut children, len: _ } => {
let i = index.child(shift);
children[i].as_mut().unwrap()
}
};
path[path_i] = Some(cnode);
path_i = path_i + 1;
node = Arc::make_mut(child);
shift = shift.dec();
}
}
The borrow-checker spits out a compilation error:
error[E0499]: cannot borrow `*cnode` as mutable more than once at a time
--> src/main.rs:108:33
|
102 | Node::Branch { ref mut children, len: _ } => {
| ---------------- first mutable borrow occurs here
...
108 | path[path_i] = Some(cnode);
| ^^^^^ second mutable borrow occurs here
...
113 | }
| - first borrow ends here
How should I approach this problem? I have tried various workarounds, but unfortunately none of them worked.
Edit #1
Here is a link to the rust playground with an executable code snippet: https://play.rust-lang.org/?gist=0e2a208a5fe5472229db30ac3d44c60d&version=nightly&mode=debug
Edit #2
I just to want to emphasize, that iterating over the data structure itself is not an issue. What I want to achieve is to have an array (see variable path in the build_path method) of mutable references to the nodes of a tree.