HashMap in Rust
The key-value map and its entry API.
use std::collections::HashMap;
fn main() {
let mut scores: HashMap<&str, i32> = HashMap::new();
scores.insert("ada", 95);
*scores.entry("ada").or_insert(0) += 5;
let ada = scores.get("ada").copied().unwrap_or(0);
let total: i32 = scores.values().sum();
println!("{ada} {total} {}", scores.len());
}
How it works
insertadds;entry().or_insertupdates in place.getreturns anOptionfor a missing key.values().sum()aggregates across the map.
Keywords and builtins used here
HashMapfni32letmainmutstruse
The run, in numbers
- Lines
- 11
- Characters to type
- 300
- Tokens
- 109
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 65 seconds.
Step 1 of 2 in Maps & counting, step 12 of 14 in Iterators & closures.