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

Ben*_*ijl 2 hashmap rust

我有两个HashMaps,并希望在某些条件下交换它们之间的值.如果第二个密钥不存在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 => {}
}
Run Code Online (Sandbox Code Playgroud)

(在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
Run Code Online (Sandbox Code Playgroud)

我对这个借用问题感到很困惑,我没有办法解决这个问题.如果我替换了Entry一个match hm.get_mut(1),我不能插入的None情况下,因为匹配可变地借用了HashMap.

log*_*yth 5

您将参考您应该提供参考的参考文献.

&mut y.get_mut()
Run Code Online (Sandbox Code Playgroud)

例如是

&mut &mut ExpensiveStruct
Run Code Online (Sandbox Code Playgroud)

你有一个类似的问题

match hm1.get_mut(&1) {
    Some(ref mut x) =>
Run Code Online (Sandbox Code Playgroud)

当类型被修剪为以下时,您的代码按预期工作&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());
Run Code Online (Sandbox Code Playgroud)

(在游乐场)

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