Back to questions
JuniorTheoryCommon
What does the program print?
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
for w in "a b a c a".split_whitespace() {
*counts.entry(w).or_insert(0) += 1;
}
println!("{} {}", counts["a"], counts["c"]);
}3 1
- Expecting every count to be 1, as if
or_insert(0)reset the value: it inserts 0 only for a missing key and otherwise returns the existing count. - Expecting the first occurrence to be skipped:
or_insertreturns a reference to the fresh 0, and+= 1raises it to 1 at once.
- Why does the counting line need the
*beforecounts.entry(w)? - How would you write the same count with
or_defaultinstead ofor_insert(0)?