std::collections::HashMap
An associative array type using hash tables, storing key-value pairs with fast lookup and insert operations.
When to Use HashMap
Use HashMap when you need fast lookups and insertions with arbitrary keys. It's ideal for caching, configuration storage, and dynamic key-value scenarios where hash-based access outperforms ordered collections.
Performance Characteristics
O(1) Average
Insert
O(1) Average
Lookup
O(n) Memory
Storage
Worst-case performance can degrade to O(n) for poor hash functions. Use high-quality hashers for production workloads.
Example Usage
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("key1", 42);
map.insert("key2", 24);
// Retrieve a value
if let Some(value) = map.get("key1") {
println!("Value: {}", value);
}
// Check if a key exists
if !map.contains_key("key3") {
println!("Key not found");
}
}
Best Practices
- Use with types that implement
Hash
andEq
- Prefer
entry
API for safe in-place modifications - When thread-safe, consider
RwLock
for concurrency>