2017-09-26 82 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()返回一個引用。