2017-09-26 51 views
2

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

不工作(简化)的关键代码如下:

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 

我真的很迷茫关于这个借用问题,我没有找到解决的办法。如果我用match hm.get_mut(1)代替Entry,我不能在None的情况下插入,因为匹配可变地借用了HashMap

回答

5

您在给出引用的地方应该引用参考。

&mut y.get_mut() 

例如是

&mut &mut ExpensiveStruct 

和您遇到

match hm1.get_mut(&1) { 
    Some(ref mut x) => 

你的代码simular问题的工作方式在类型下调至&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()返回一个引用。