0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
xji
  • 7,341
  • 4
  • 40
  • 61
  • What prevents your code from having mutable aliases, which is [forbidden in safe Rust](https://doc.rust-lang.org/stable/book/references-and-borrowing.html#the-rules)? – Shepmaster Dec 01 '16 at 21:22
  • @Shepmaster Sorry, forgot to include that. Was in another file. It currently just contains a function definition. I now included it. – xji Dec 01 '16 at 21:27
  • 1
    Are you ready for some deep magic? [This works](http://play.integer32.com/?gist=4638635a652364baf0d30038c932d315&version=stable). You can find an explanation on the [duplicate question](http://stackoverflow.com/q/37986640/155423). – Shepmaster Dec 01 '16 at 21:57

0 Answers0