I need to insert a node in a tree in a way roughly like below:
pub struct Node {
data: Vec<u64>,
nodes: Vec<Box<Node>>,
}
pub struct Tree {
root: Box<Node>,
}
impl Tree {
pub fn insert(&mut self, data: Vec<u64>) {
let mut current = &mut self.root;
let mut index = 0;
loop {
if let Some(child) = current.nodes.get_mut(index) {
index += 1;
current = child;
} else {
let node = Node {
data,
nodes: Vec::default(),
};
current.nodes.push(Box::new(node));
return;
}
}
}
}
but I get the error:
error[E0499]: cannot borrow `current.nodes` as mutable more than once at a time
--> src/tree.rs:25:17
|
16 | if let Some(child) = current.nodes.get_mut(index) {
| ------------- first mutable borrow occurs here
...
25 | current.nodes.push(Box::new(node));
| ^^^^^^^^^^^^^
| |
| second mutable borrow occurs here
| first borrow later used here
How can I solve this efficiently?