HashMap

HashMap get and entry APIs, key borrowing, unstable iteration order, and when to use BTreeMap instead.

主题页正文目前为英文。

HashMap<K, V> is a standard-library type in std::collections. It is not a module, and it is not a third-party crate. Keys must implement Eq + Hash. get borrows the map and looks up a key through the Borrow trait, so a HashMap<String, _> can be queried with a &str.

Iteration order of a HashMap is not stable and must not be part of an expected output. When a report has to be deterministic, collect and sort the keys, or use BTreeMap, which iterates in key order. {:?} of a HashMap is also unordered; do not hard-code that Debug text.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
HashMap::insert, HashMap::get, HashMap::entryStore 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.
BTreeMap iterationUse BTreeMap when a report must list changed keys consistently, then handle missing keys explicitly.

get, insert, and entry

insert takes ownership of the key and value and returns the previous value, if any. get returns Option<&V>. The entry API takes &mut self and a key, then lets you update a vacant or occupied slot without a second lookup. Because get borrows the map, you cannot hold that reference and call a &mut self method such as entry or insert at the same time.

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.

ParameterDescription
k / keyinsert 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.
vThe 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.
rust
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=10

Related: HashMap::entry, Entry

Official documentation →

Compare values in key order

When a report must list keys in a consistent order, BTreeMap is the standard-library map that iterates in key order. HashMap cannot provide that guarantee. The example checks existing keys for changes; finding added keys requires iterating the new map as well.

BTreeMap iteration

// BTreeMap<K, V> iterates in key order when K: Ord

Use BTreeMap when a report must list changed keys consistently, then handle missing keys explicitly.

  • This example is the original Rust reference recipe; the section id is unchanged.
  • BTreeMap is also in std::collections. It is a different type from HashMap, not a configuration option of HashMap.
rust
use std::collections::BTreeMap;

fn main() {
    let before = BTreeMap::from([("timeout", 10), ("port", 80)]);
    let after = BTreeMap::from([("port", 8080), ("timeout", 0)]);
    for (key, old) in &before {
        if let Some(current) = after.get(key) {
            if current != old {
                println!("{key}: {old} -> {current}");
            }
        }
    }
}

Expected output

port: 80 -> 8080
timeout: 10 -> 0

Related: Original recipe on the Rust overview, BTreeMap

Official documentation →