如果不能,"不能一次多次借用可变的东西"

Fre*_*ang 0 rust

我正在编写一个程序来计算单词出现的频率.这是我的代码的一部分.

// hm is a HashMap<&str, u32>
if let Some(val) = hm.get_mut(tt) {
    *val += 1u32;
} else {
    hm.insert(tt.clone(), 1u32);
}
Run Code Online (Sandbox Code Playgroud)

我得到了......

error: cannot borrow `hm` as mutable more than once at a time [E0499]
      hm.insert(tt.clone(), 1u32);
      ^~
note: first mutable borrow occurs here
            if let Some(val) = hm.get_mut(tt) {
                            ^~
note: first borrow ends here
            }
            ^
help: run `rustc --explain E0499` to see a detailed explanation
Run Code Online (Sandbox Code Playgroud)

我可以通过hm.insert()移出else范围来绕过这个但是它是一种"非程序化"的方式......我尝试使用match但是同样的错误(很明显)会发生.

我怎样才能解决这个问题?

Chr*_*ern 5

这是HashMapRust中s 的常见问题:借用不能有粗糙的边缘.幸运的是,有一个API来处理这种情况.

您可以使用HashMap::entry()哈希映射,占用或空置的位置,然后使用or_insert()设置密钥的值(如果没有密钥).

*hm.entry(tt).or_insert(0u32) += 1;
Run Code Online (Sandbox Code Playgroud)

这将返回对该hm位置的引用,如果它不存在则填充0,然后增加它的任何内容.

Rust的生命周期容易发生无端冲突并不是一个未知的问题.这是Rust的Rust核心团队成员,讨论在未来版本的Rust中解决这个问题的计划.但是现在,有一些库方法可以解决它.