【问题标题】:How to workaround Rust's borrow check of HashMap? [duplicate]如何解决 Rust 对 HashMap 的借用检查? [复制]
【发布时间】:2016-04-13 16:03:40
【问题描述】:

我有这段代码,其中pat_vecstr_vec 是两个迭代器:

let mut pat_mapping: HashMap<char, &str> = HashMap::new();

for combi in pat_vec.zip(str_vec) {
    let (c, word) = combi;

    match pat_mapping.get(&c) {
        Some(phrase) => {
            if phrase.to_string() != word.to_string() {
                return false;
            }
        }

        None => {
            pat_mapping.insert(c, word);
        }
    }
}

这不起作用,编译器抱怨:

cannot borrow `pat_mapping` as mutable because it is also borrowed as immutable [E0502]

我知道这可能是因为pat_mapping.get(&amp;c) 借用了&amp;self 作为不可变,而insert() 方法属于同一范围但需要借用&amp;self 作为可变。

我有一个解决方法:

match word_mapping.get(&c) {
    Some(phrase) => {
        if phrase.to_string() != word.to_string() {
            return false;
        }
    }
    None => {

        pat_trigger = true;
    }

};

if pat_trigger {
    pat_mapping.insert(c, word);
}

但是引入布尔标志是多余的。有没有办法绕过借用检查,以便在同一个代码块中进行匹配和插入?

【问题讨论】:

    标签: hashmap rust match


    【解决方案1】:

    你想使用entry:

    match pat_mapping.entry(c) {
        Occupied(phrase) => {
            if phrase.get().to_string() != word.to_string() {
                return false;
            }
        },
        Vacant(vacant) => {
            vacant.insert(word);
        }
    }
    

    它还具有只查找一次密钥的优点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      相关资源
      最近更新 更多