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
。