#Using the Entry API on HashMap
15 messages · Page 1 of 1 (latest)
This lets me insert a value if it is missing: letters.entry(ch).or_insert(0);
If I insert a value, I would not like to add onto it though
then use and_modify first
use std::collections::HashMap;
let mut map: HashMap<&str, u32> = HashMap::new();
map.entry("poneyland")
.and_modify(|e| { *e += 1 })
.or_insert(42);
assert_eq!(map["poneyland"], 42);
map.entry("poneyland")
.and_modify(|e| { *e += 1 })
.or_insert(42);
assert_eq!(map["poneyland"], 43);
So this line is not needed, when inserting new value : *counter += 1;
Use .and_modify(|c|...).or_insert(0)
ohhh
A view into a single entry in a map, which may either be vacant or occupied.
(or manually match on Entry, its variants' contents' have more methods).
But yeah, this can be done with and_modify
So and_modify only works if there is an entry?
it only runs if there's an entry
and or_insert only works if there is no entry?
Yes
Entry always exists, but it can be a VacantEntry or an OccupiedEntry.
and_modify only runs if it's occupied, and or_insert only inserts if it's vacant.