Wie lookup aus und legen Sie in eine HashMap effizient?

Möchte ich Folgendes tun:

  • Nachschlagen Vec für einen bestimmten Schlüssel, und bewahren Sie Sie für späteren Gebrauch auf.
  • Wenn es nicht vorhanden ist, erstellen Sie eine leere Vec für den Schlüssel, aber immer noch halten Sie es in die variable.

Wie dies effizient? Natürlich dachte ich, könnte ich 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
    }
};

Wenn ich es versuchte, es gab mir Fehler, wie:

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

Landete ich mit etwas wie das zu tun, aber ich weiß nicht, wie die Tatsache, dass es führt die Suche zweimal (map.contains_key und map.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!");
    }
};

Gibt es einen sicheren Weg, dies zu tun mit nur einem match?

InformationsquelleAutor Yusuke Shinyama | 2015-02-14

Schreibe einen Kommentar