I'm trying to implement a recursive insertion on a trie but got stuck with the error: "cannot assign to cur_node
because it is borrowed", "cannot borrow *cur_node
as mutable more than once at a time".
pub trait Trie {
fn insert_word(&mut self, word: &str);
}
pub struct VectorTrie {
edges: Vec<Edge>,
}
pub struct Edge {
ch: char,
to: VectorTrie,
}
impl Trie for VectorTrie {
fn insert_word(&mut self, word: &str) {
let mut cur_node = self;
for ch in word.chars() {
cur_node = cur_node.get_or_create(ch);
}
}
}
impl VectorTrie {
pub fn get_or_create(&mut self, ch: char) -> &mut VectorTrie {
match self.edges.binary_search_by(|e| e.ch.cmp(&ch)) {
Ok(idx) => &mut self.edges[idx].to,
Err(idx) => {
let to = VectorTrie { edges: Vec::new() };
let e = Edge { ch: ch, to: to };
self.edges.insert(idx, e);
&mut self.edges[idx].to
}
}
}
}
However, what I wanted to do is just to recursively insert the individual characters in a word by taking the Node("VectorTrie")
returned by each insertion and continuing to insert the next character to that Node
.
No doubt the error is again because I tried to apply C logic to Rust... I'm trying to create the cur_node
variable as a temporary reference, modifiable on each loop, though apparently this is not happening here. What should be the idiomatic way to achieve my aim in Rust then?