31. HashMap's entry API
Want to insert a value into a HashMap only if the key doesn’t exist yet? Skip the double lookup — use the entry API.
| |
The entry API returns an Entry enum — either Occupied or Vacant. The convenience methods make common patterns a one-liner:
| |
or_insert(val) inserts a default, or_insert_with(|| val) lazily computes it, and or_default() uses the type’s Default. All three return a mutable reference to the value, so you can update in place.