HashMaps in Rust
| HashMap::new | |
| Entry API | |
| Iterate | |
| Word counter |
HashMap::new
A HashMap stores key value pairs with fast lookup by key. Import it from the collections module, then insert owned keys with their scores, counts, or settings.
Key and value types come from use, so an explicit annotation is rarely needed for small maps.
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("blue"), 10);
}
The map starts empty and gains one team score. Later inserts with the same key replace the old value in place.
Entry API
The entry API updates a key whether or not it exists yet. It looks up the slot once, inserts a default on absence, and hands back a mutable view of the value.
This removes the classic check then insert dance and keeps counters and caches short.
use std::collections::HashMap;
fn main() {
let mut m = HashMap::new();
m.entry(String::from("a")).or_insert(0);
}
The key a appears with 0 on first touch. Repeating the line leaves the stored value unchanged since the slot already exists.
Iterate
Loops over a map yield one key value pair per step. Borrow the map to keep ownership, and each pair arrives as references to the stored key and value.
Order is not promised, so sort keys first when output must look stable across runs.
use std::collections::HashMap;
fn main() {
let mut m = HashMap::new();
m.insert(String::from("a"), 1);
for (k, v) in &m {
println!("pair");
}
}
The loop borrows m and visits each pair once. The map stays fully usable after the loop because nothing moved out.
Word counter
Counters combine splitting and the entry API. Split text into words, look up each word slot, and bump the stored number through the mutable view.
The whole histogram fits in a few lines with no manual branch for first sightings.
use std::collections::HashMap;
fn main() {
let mut count = HashMap::new();
for w in "a b a".split_whitespace() {
*count.entry(w).or_insert(0) += 1;
}
}
The sample text yields two for a and one for b. Each new word starts at 0 and the star writes the bumped total back.
Next: Modules
Article author: Arthur Isaev