I just started reading a book on Rust so I don't understand the issues fully yet. I need a workaround, not a lecture on Rust theory. Lines that cause compiler errors are at 39 and 41. The first problem seems to be that I am using a recursive instance method on &mut self.
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:38:30
|
32 | let mut node = &mut self.nodes[index as usize];
| ---------- first mutable borrow occurs here
...
38 | node.leftindex = self.insertrec(node.leftindex, num);
| ^^^^ -------------- first borrow later used here
| |
| second mutable borrow occurs here
error[E0502]: cannot borrow `*self` as immutable because it is also borrowed as mutable
--> src/main.rs:40:30
|
32 | let mut node = &mut self.nodes[index as usize];
| ---------- mutable borrow occurs here
...
40 | node.leftcount = self.count(node.leftindex);
| ^^^^ -------------- mutable borrow later used here
| |
| immutable borrow occurs here
Full code is here:
struct BstTree {
nodes: Vec<BstNode>,
root: i32,
}
struct BstNode {
num: i32,
leftindex: i32,
rightindex: i32,
leftcount: i32,
rightcount: i32,
}
const NULL: i32 = -1;
impl BstTree {
fn new(capacity: i32) -> BstTree {
return BstTree {
nodes: Vec::<BstNode>::with_capacity(capacity as usize),
root: NULL,
};
}
fn insert(&mut self, num: i32) {
self.root = self.insertrec(self.root, num);
}
fn insertrec(&mut self, index: i32, num: i32) -> i32 {
if index == NULL {
return self.allocate(num);
}
let mut node = &mut self.nodes[index as usize];
if num == node.num {
return index;
}
if num < node.num {
// error[E0499]: cannot borrow `*self` as mutable more than once at a time
node.leftindex = self.insertrec(node.leftindex, num);
// error[E0502]: cannot borrow `*self` as immutable because it is also borrowed as mutable
node.leftcount = self.count(node.leftindex);
}
0
}
fn count(&self, index: i32) -> i32 {
assert!(index != NULL);
let node = &self.nodes[index as usize];
return node.leftcount + node.rightcount + 1;
}
fn allocate(&mut self, num: i32) -> i32 {
self.nodes.push(BstNode {
num: num,
leftindex: NULL,
rightindex: NULL,
leftcount: 0,
rightcount: 0,
});
let index = self.nodes.len() - 1;
return index as i32;
}
}
fn main() {
let mut bst = BstTree::new(10000);
bst.insert(5);
bst.insert(8);
bst.insert(11);
bst.insert(10);
bst.insert(9);
bst.insert(4);
bst.insert(3);
}