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 => {}
}
我得到的錯誤:
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
。