HashMap::insert, HashMap::get, HashMap::entry
fn insert(&mut self, k: K, v: V) -> Option<V>
fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
where K: Borrow<Q>, Q: Hash + Eq
fn entry(&mut self, key: K) -> Entry<'_, K, V>Store and look up values by key. get borrows; entry lets you insert or modify in one lookup. Print HashMap contents in a sorted key order when the output must be deterministic.
| Parameter | Description |
|---|---|
k / key | insert and entry take an owned key. get takes a borrowed query type that the key can be borrowed as, such as &str for a String key. |
v | The value to store. insert overwrites an existing key and returns the old value as Some. |
Returns: insert returns Option<V> with the previous value. get returns Option<&V> borrowed from the map. entry returns an Entry enum with or_insert and and_modify methods.
- The printed lines are produced by sorting the keys. Running the same inserts and then iterating the map directly can print these keys in a different order.
- map[key] also exists through Index and panics when the key is missing, similar to Vec indexing. This example uses it only after the key was taken from the map itself.
- entry("port").and_modify(...) leaves a missing key unchanged; or_insert adds a key only when it is vacant.
use std::collections::HashMap;
fn main() {
let mut map: HashMap<&str, i32> = HashMap::new();
map.insert("timeout", 10);
map.insert("port", 80);
println!("get port={:?} get host={:?}", map.get("port"), map.get("host"));
map.entry("port").and_modify(|value| *value = 8080);
map.entry("retries").or_insert(3);
let mut keys: Vec<_> = map.keys().copied().collect();
keys.sort();
for key in keys {
println!("{key}={}", map[key]);
}
}Expected output
get port=Some(80) get host=None
port=8080
retries=3
timeout=10Related: HashMap::entry, Entry