HashMap<K, V> (Rust)
HashMap<K, V> stores key–value pairs with fast average O(1) lookup by key. It is Rust's standard hash table, equivalent to a dictionary or map in other languages.
Rust
A HashMap maps keys of type K to values of type V. Insert with .insert(k, v), look up with .get(&k) (returns Option<&V>), and the .entry() API handles 'insert if missing, otherwise update' cleanly. Keys must implement Eq and Hash.
It is not in the prelude, so you import it with use std::collections::HashMap. Iteration order is unspecified (and randomized for DoS resistance); use a BTreeMap when you need keys in sorted order.
Ownership applies as usual: inserting an owned value (like a String) moves it into the map. .get returns a reference, so you borrow values out rather than moving them. The entry API is the idiomatic way to count or accumulate.
Syntax
use std::collections::HashMap;
let mut m: HashMap<String, i32> = HashMap::new();
m.insert("a".to_string(), 1);Examples
Rust
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("ana", 10);
*scores.entry("ana").or_insert(0) += 5;
println!("{}", scores["ana"]);
}Output:
15