🦀 Rust Intermediate

What is a HashMap in Rust and how is it used?

Answer

HashMap<K, V> is Rust's standard hash map in std::collections. Create one with HashMap::new() or use collect() on an iterator of tuples. Insert with map.insert(key, value) (returns the old value if the key existed). Access with map.get(&key) (returns Option<&V>) or map[&key] (panics if missing). The entry API is the idiomatic way to insert-or-update: map.entry(key).or_insert(default) inserts only if the key is absent and returns a mutable reference to the value. Iterate over key-value pairs with for (k, v) in &map. Keys must implement Eq and Hash. By default, Rust uses a DoS-resistant hashing algorithm (SipHash). For performance-critical code, consider FxHashMap or AHashMap from external crates.