Adding a Key and Value Only If a Key Isn't Present
It's common to check whether a particular key already exists in the hash map with a value and then to take the following actions: if the key does exist in the hash map, the existing value should remain the way it is; if the key doesn't exist, insert it and a value for it.
Hash maps have a special API for this called entry
that takes the key you want to check as a parameter. The return value of the entry
method is an enum called Entry
that represents a value that might or might not exist. Let's say we want to check whether the key for the Yellow team has a value associated with it. If it doesn't, we want to insert the value 50
, and the same for the Blue team. Using the entry
API, the code looks like Listing 8-24.
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.entry(String::from("Yellow")).or_insert(50);
scores.entry(String::from("Blue")).or_insert(50);
println!("{:?}", scores);
Listing 8-24: Using the entry
method to only insert if the key does not already have a value
The or_insert
method on Entry
is defined to return a mutable reference to the value for the corresponding Entry
key if that key exists, and if not, it inserts the parameter as the new value for this key and returns a mutable reference to the new value. This technique is much cleaner than writing the logic ourselves and, in addition, plays more nicely with the borrow checker.
Running the code in Listing 8-24 will print {"Yellow": 50, "Blue": 10}
. The first call to entry
will insert the key for the Yellow team with the value 50
because the Yellow team doesn't have a value already. The second call to entry
will not change the hash map because the Blue team already has the value 10
.