capypad
0 day streak
rust / intermediate
Snippet

HashMap Entry API for Key Management

The Entry API provides ergonomic key insertion with fallbacks. or_insert inserts the value if the key is absent, otherwise leaves the existing value untouched. This pattern avoids redundant lookups common with get followed by insert.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
use std::collections::HashMap;
 
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Red"), 50);
 
scores.entry(String::from("Blue")).or_insert(100);
scores.entry(String::from("Red")).or_insert(100);
 
println!("{:?}", scores);
}
Breakdown
1
scores.entry(String::from("Blue")).or_insert(100);
Entry for "Blue" doesn't exist, so inserts value 100
2
scores.entry(String::from("Red")).or_insert(100);
Entry for "Red" already exists, so leaves current value 50