#Using the Entry API on HashMap

15 messages · Page 1 of 1 (latest)

toxic escarp
#
use std::collections::HashMap;
let mut letters = HashMap::new();
for ch in "a short treatise on fungi".chars() {    
    let counter = letters.entry(ch).or_insert(0); 
   *counter += 1;
}

I saw this in the docs, I would like to:

  • Insert a value if it is empty
  • Add onto an existing value if it is there
#

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

maiden umbra
#

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);
toxic escarp
#

So this line is not needed, when inserting new value : *counter += 1;

digital peak
#

Use .and_modify(|c|...).or_insert(0)

toxic escarp
#

ohhh

maiden umbra
eternal jewel
#

(or manually match on Entry, its variants' contents' have more methods).

But yeah, this can be done with and_modify

toxic escarp
#

So and_modify only works if there is an entry?

maiden umbra
#

it only runs if there's an entry

toxic escarp
#

and or_insert only works if there is no entry?

marble swallow
#

Yes

eternal jewel
#

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.