Rust hashmap :: get, if None, insert default, return default

In HashMap in std::collections - Rust
I could not find a function for doing the following:

lookup key k, if it exists, return associated value
if it does not exist, then insert default value d, and return ref to d

Is there an idiomatic way to do this in Rust?

let val = m.entry(k).or_insert(d)

4 Likes

And in cases where the value type implements the Default trait, you can also use:

map.entry(k).or_default()
9 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.