The entry API in Rust
One lookup instead of two: entry gives you the slot, occupied or not.
use std::collections::HashMap;
fn main() {
let text = "the quick the lazy the end";
let mut counts: HashMap<&str, u32> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
let mut groups: HashMap<usize, Vec<&str>> = HashMap::new();
for word in text.split_whitespace() {
groups.entry(word.len()).or_insert_with(Vec::new).push(word);
}
println!("{}", counts["the"]);
println!("{:?}", groups.get(&4));
}
How it works
or_insertreturns a mutable reference to the value.or_insert_withbuilds the default only when it is needed.*count += 1writes through that reference.
Keywords and builtins used here
HashMapVecfnforinletmainmutstru32useusize
The run, in numbers
- Lines
- 18
- Characters to type
- 448
- Tokens
- 147
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 98 seconds.
Step 5 of 8 in Collections, step 34 of 39 in Language basics.