Being fairly new to Rust, I was wondering on how to create a HashMap
with a default value for a key? For example, having a default value 0
for any key inserted in the HashMap
.
In Rust, I know this creates an empty HashMap:
let mut mymap: HashMap<char, usize> = HashMap::new();
I am looking to maintain a counter for a set of keys, for which one way to go about it seems to be:
for ch in "AABCCDDD".chars() {
mymap.insert(ch, 0)
}
Is there a way to do it in a much better way in Rust, maybe something equivalent to what Ruby provides:
mymap = Hash.new(0)
mymap["b"] = 1
mymap["a"] # 0
Answering the problem you have...
Then you want to look at How to lookup from and insert into a HashMap efficiently?. Hint:
*map.entry(key).or_insert(0) += 1
Answering the question you asked...
No,
HashMap
s do not have a place to store a default. Doing so would cause every user of that data structure to allocate space to store it, which would be a waste. You'd also have to handle the case where there is no appropriate default, or when a default cannot be easily created.Instead, you can look up a value using
HashMap::get
and provide a default if it's missing usingOption::unwrap_or
:Of course, you are welcome to wrap this in a function or a data structure to provide a nicer API.
ArtemGr brings up an interesting point:
Rust adds an additional wrinkle to this. Actually inserting a value would require that simply getting a value can also change the
HashMap
. This would invalidate any existing references to values in theHashMap
, as a reallocation might be required. Thus you'd no longer be able to get references to two values at the same time! That would be very restrictive.What about using
entry
to get an element from the HashMap, and then modify it.From the docs:
example