Trie data structure: a problem of multiple mutable references
Hi everyone, I'm trying to implement a Trie in rust but I'm stuck with this error:
error: cannot borrow `*self` as mutable more than once at a time
The problem lies in the insert funcion:
fn insert(&mut self, word: &str) {
let word: Vec<_> = word.chars().collect(); // first mutable borrow
let node: &mut TNode = &mut self.root; // first borrow later used here
self.insert_rec(node, &word, 0);
}
After some research I found this example.
It shows a basic usage of Rc and RefCell, if possible I'd like to avoid that.
I managed to make it work with an iterative approach.
But I'd like to know how can I achieve the same with a recursive function (and why the borrow checker "breaks" inside recursive functions?).
fn insert_iter(&mut self, word: &str) {
let word: Vec<_> = word.chars().collect();
let mut node: &mut TNode = &mut self.root;
for i in 0..word.len() {
let current = word[i];
if !node.children.contains_key(¤t) {
let is_end = i == word.len() - 1;
node.children
.insert(current, TNode::new(current, is_end, None));
}
node = node.children.get_mut(¤t).unwrap();
}
}
You can't call a method on &mut self whlie also passing a reference to &mut self.root, even if inside of the insert_rec function you don't use self.root.
There was some blog post about "lifetime view" types or something that could maybe help with this but I can't seem find it.
Can you extract the body of the insert_rec function into an associated function/standalone function that just takes the pieces it needs (and re-use it to define insert_rec for deduplication)?