在两个哈希映射之间交换值

时间:2017-09-26 19:51:23

标签: hashmap rust

我有两个HashMap,并希望在某些条件下交换它们之间的值。如果第二个HashMap中不存在该密钥,则应插入该密钥。我不想克隆这个值,因为那太贵了。

无效的(简化)关键代码如下:

match hm1.get_mut(&1) {
    Some(ref mut x) => match hm.entry(1) {
        Entry::Occupied(mut y) => if y.get().replace {
            mem::swap(x, &mut y.get_mut());
        },
        Entry::Vacant(y) => {
            y.insert(mem::replace(x, dummy));
        }
    },
    None => {}
}

(在Rust Playground上)

我收到错误:

error[E0597]: `y` does not live long enough
  --> src/main.rs:28:9
   |
23 |                 mem::swap(x, &mut y.get_mut());
   |                                   - borrow occurs here
...
28 |         },
   |         ^ `y` dropped here while still borrowed
29 |         None => {}
30 |     }
   |     - borrowed value needs to live until here

我对这个借用问题感到很困惑,我没有办法解决这个问题。如果我将Entry替换为match hm.get_mut(1),我无法在None案例中插入,因为匹配会错误地借用HashMap

1 个答案:

答案 0 :(得分:5)

您提供了参考资料的参考资料。

&mut y.get_mut()

例如是

&mut &mut ExpensiveStruct

你和

有类似的问题
match hm1.get_mut(&1) {
    Some(ref mut x) =>

当类型被裁减为&mut ExpensiveStruct时,您的代码按预期工作:

match hm1.get_mut(&1) {
    Some(x) => match hm.entry(1) {
        Entry::Occupied(mut y) => if y.get().replace {
            mem::swap(x, y.get_mut());

On the Playground

请注意,ref mut已被删除,因为hm1.get_mut(&1)已经为可变引用返回Option,并且&mut已被删除,因为y.get_mut()已经返回参考。

相关问题