1

We have a simple pattern of "get or create" which I was able to implement as shown below. However, we couldn't find an efficient way to avoid this insert followed by get of the value which we just created. Is there a way to write this in a more concise way?

let value = match map.get_mut(key) {
    Some(v) => v,
    None => {
        let v = Value::new();
        map.insert(key.to_owned(), v);
        map.get_mut(key).unwrap()
    }
};
Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
Guy Korland
  • 9,139
  • 14
  • 59
  • 106
  • 1
    Hi there. I think your question is answered by [this Q&A](https://stackoverflow.com/questions/28512394/how-to-lookup-from-and-insert-into-a-hashmap-efficiently). Summary: use the `entry` API, i.e. `map.entry(key).or_insert_with(|| Value::new())`. Please let us know if this indeed answers your question! – Lukas Kalbertodt Sep 10 '19 at 10:58
  • @LukasKalbertodt thanks it seems like can be a nice solution, the only problem with .entry() is that it requires key ownership even when the key already exists. `map.entry(key.to_owned()).or_insert_with(|| Value::new())` – Guy Korland Sep 10 '19 at 12:07

0 Answers0