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

In std::collections::HashMap - 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)


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


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.