Entry API and Defaults
Update values ergonomically.
Why the Entry API?
Often you want to update a value if a key exists, or insert a default if it does not.
Doing this with get plus insert is clumsy. The entry API does it cleanly in one step.
entry Returns a Slot
Calling entry(key) gives you a handle to that key's place in the map.
From that handle you decide what to do: fill it with a default, or modify whatever is there.
use std::collections::HashMap;
fn main() {
let mut m: HashMap<&str, i32> = HashMap::new();
m.entry("a").or_insert(0);
println!("{}", m["a"]);
}All lessons in this course
- Building a HashMap
- Entry API and Defaults
- Working with HashSet
- Counting and Grouping