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.
Previous
What are Rust's concurrency primitives (Send and Sync traits)?
Next
What are zero-cost abstractions and monomorphization in Rust?
More Rust Questions
View all →- Intermediate How does error handling with the ? operator work in Rust?
- Intermediate What are the thiserror and anyhow crates for error handling?
- Intermediate What are trait objects (dyn Trait) in Rust?
- Intermediate What are generics in Rust and how do where clauses work?
- Intermediate What are Rust smart pointers?