问题
When using hash maps, it is common to want to add a key:value pair if the key is not already present.
This reads well but isn't as optimal as it could be.
if !map.contains(key) {
let val = create_val();
map.insert(key, val);
some_creation_logic(val);
} else {
let val = map[key];
some_update_logic(val);
}
While this works it will always do 2 lookups.
The closest I could get was to use Entry.or_insert (or or_insert_with), counting the length so the else branch can be taken.
let map_len_prev = map.len();
let val = map.or_insert_with(key, create_val);
if map_len_prev != map.len() {
some_creation_logic(val);
} else {
some_update_logic(val);
}
Is there a clearer way to insert a value when needed while keeping a way of running both branches of logic for cases it does/doesn't already exist?
回答1:
You can just match the Entry:
use std::collections::hash_map::Entry::{Occupied, Vacant};
match map.entry(key) {
Occupied(val) => {
some_update_logic(val.get());
},
Vacant(entry) => {
let val = entry.insert(create_val());
some_creation_logic(val);
}
}
来源:https://stackoverflow.com/questions/39560296/best-way-to-conditionally-add-to-a-hashmap-with-as-few-lookups-as-possible