如何有效地从HashMap中查找和插入?

Yus*_*ama 83 lookup hashmap rust

我想做以下事情:

  • 查找Vec某个键,并将其存储起来供以后使用.
  • 如果它不存在,Vec则为该键创建一个空,但仍将其保留在变量中.

如何有效地做到这一点?当然我以为我可以使用match:

use std::collections::HashMap;

// This code doesn't compile.
let mut map = HashMap::new();
let key = "foo";
let values: &Vec<isize> = match map.get(key) {
    Some(v) => v,
    None => {
        let default: Vec<isize> = Vec::new();
        map.insert(key, default);
        &default
    }
};
Run Code Online (Sandbox Code Playgroud)

当我尝试它时,它给了我错误,如:

error[E0502]: cannot borrow `map` as mutable because it is also borrowed as immutable
  --> src/main.rs:11:13
   |
7  |     let values: &Vec<isize> = match map.get(key) {
   |                                     --- immutable borrow occurs here
...
11 |             map.insert(key, default);
   |             ^^^ mutable borrow occurs here
...
15 | }
   | - immutable borrow ends here
Run Code Online (Sandbox Code Playgroud)

我最终做了类似的事情,但我不喜欢它执行两次查询(map.contains_keymap.get)的事实:

// This code does compile.
let mut map = HashMap::new();
let key = "foo";
if !map.contains_key(key) {
    let default: Vec<isize> = Vec::new();
    map.insert(key, default);
}
let values: &Vec<isize> = match map.get(key) {
    Some(v) => v,
    None => {
        panic!("impossiburu!");
    }
};
Run Code Online (Sandbox Code Playgroud)

只有一个安全的方法match吗?

huo*_*uon 101

entryAPI是专为这一点.在手动形式,它可能看起来像

use std::collections::hash_map::Entry;

let values: &Vec<isize> = match map.entry(key) {
    Entry::Occupied(o) => o.into_mut(),
    Entry::Vacant(v) => v.insert(default)
};
Run Code Online (Sandbox Code Playgroud)

或者可以使用简短的形式:

map.entry(key).or_insert_with(|| default)
Run Code Online (Sandbox Code Playgroud)

default即使没有插入,如果计算好/便宜,它也可以是:

map.entry(key).or_insert(default)
Run Code Online (Sandbox Code Playgroud)

  • entry()的问题是,你总是要克隆密钥,有没有办法避免这种情况? (19认同)