capypad
0 day streak
rust / intermediate
Snippet

Efficient Map Updates with the Entry API

The Entry API allows you to check for a key's existence and perform an operation in a single step, avoiding double lookups and providing a more expressive way to handle conditional insertion.

snippet.rs
rust
1
2
3
4
5
6
7
8
use std::collections::HashMap;
 
let mut scores = HashMap::new();
let team = String::from("Blue");
 
scores.entry(team).and_modify(|e| *e += 10).or_insert(50);
 
println!("{:?}", scores);
Breakdown
1
scores.entry(team)
Returns an Entry enum representing either an occupied or vacant spot.
2
and_modify(|e| *e += 10)
Applies a closure to the value if the entry is already occupied.
3
or_insert(50)
Inserts the provided value if the entry is vacant, returning a mutable reference.