如何在循环中更新可变引用?

How can I update a mutable reference in a loop?

我正在尝试用 Rust 实现一个 Trie/Prefix 树,但我在使用借用检查器时遇到了问题。到目前为止,这是我的实现,当我调用 children.insert.

时出现错误

cannot borrow *children as mutable because it is also borrowed as immutable

use std::collections::HashMap;

#[derive(Clone, Debug)]
struct PrefixTree {
    value: String,
    children: HashMap<char, PrefixTree>
}

fn insert(mut tree: &mut PrefixTree, key: &str, value: String) {

    let mut children = &mut tree.children;

    for c in key.chars() {    
        if !children.contains_key(&c) {
            children.insert(c, PrefixTree {
                value: String::from(&value),
                children: HashMap::new()
            });
        }
        
        let subtree = children.get(&c);

        match subtree {
            Some(s) => {
                children = &mut s.children;
            },
            _ => {}
        }
    }
    tree.value = value;

}

fn main() {

    let mut trie = PrefixTree {
        value: String::new(),
        children: HashMap::new()
    };

    let words = vec!["Abc", "Abca"];

    for word in words.iter() {
        insert(&mut trie, word, String::from("TEST"));        
    }

    println!("{:#?}", trie);
}

我认为这个问题与 有关,但在我的情况下,我需要更新可变引用并继续循环。我明白为什么会出现错误,因为我两次借用了一个可变引用,但我对如何重写它感到困惑,所以我没有那样做。

当您使用一个键执行多项操作(如查找或插入和获取)并且 运行 遇到借用麻烦时,请尝试使用 Entry API(通过 .entry()):

fn insert(mut tree: &mut PrefixTree, key: &str, value: String) {
    let mut children = &mut tree.children;

    for c in key.chars() {
        let tree = children.entry(c).or_insert_with(|| PrefixTree {
            value: String::from(&value),
            children: HashMap::new(),
        });

        children = &mut tree.children;
    }
    
    tree.value = value;
}