【问题标题】:How can I update a mutable reference in a loop?如何在循环中更新可变引用?
【发布时间】:2022-01-02 00:01:04
【问题描述】:

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

不能将*children 借用为可变的,因为它也被借用为不可变的

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);
}

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

【问题讨论】:

    标签: rust reference borrow-checker


    【解决方案1】:

    当您使用单个键(如查找或插入和获取)执行多项操作并遇到借用问题时,请尝试使用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;
    }
    

    【讨论】:

    • 我不知道 Entry API。感谢您的帮助!
    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 2022-08-08
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多