How to build a Trie without borrow multiple times[E0499]

Hi, all:
I want to build a tree below, but I'm stuck with the E0499.
Any hints?

#[cfg(test)]
    impl Node {
        fn new() -> Self {
            Self { text: "".to_string(), children: vec![] }
        }

        fn add_child(&mut self, node: Node) {
            self.children.push(node);
        }
    }

    #[test]
    fn test_node() {
        // root
        // |
        // a ------- b
        // |----|    |
        // a    b    a
        let mut root = Node::new();
        let vec_s = vec!["a", "b", "aa", "ab", "ba"];
        for s in vec_s {
            let mut p_node = &mut root;
            for c in s.as_bytes() {
                let idx:usize = (c - 96) as usize;
                let node = p_node.children.get_mut(idx);
                if node.is_some() {
                    p_node = node.unwrap();
                } else {
                    p_node.add_child(Node::new());
                }
            }
        }
    }
}

To show error messages in a forum post, please execute cargo check (or other cargo build commands) for your crate on the command line and copy the full error message (usually starting with a line that starts “error:” and ending when the next error or warning begins) that the compiler gives you.

2 Likes

Try not borrowing outside of the conditional blocks.

            if idx < p_node.children.len() {
                p_node = &mut p_node.children[idx];
            } else {
                p_node.add_child(Node::new());
            }

sorry for that, the terminal cargo check prints too much things.
I mean to use the CLION's cargo check to make things easier.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.