I have a HashMap and would like to update a value if it exists and otherwise add a default one. Normally I would do it like this:
some_map.entry(some_key)
.and_modify(|e| modify(e))
.or_insert(default)
But now my modify has type fn(T)->T, but the borrow checker obviously won’t allow me to write:
some_map.entry(some_key)
.and_modify(|e| *e = modify(*e))
.or_insert(default)
What is the preferred way of doing this in Rust? Should I just use remove and insert?
Assuming you can create an empty version of your
Tfor cheap, you could usemem::replace:this assumes
modifydoes not panic though, otherwise you'll find yourself with the "empty" value staying in your map. But you'd have a similar issue withremove/insert.