4 ms·
I didn’t get past the first limitation before my brain started itching. Wouldn’t the approach there be to avoid mutating the same string (and thus reborrowing
by rolandrodriguez 2y ago
I didn’t get past the first limitation before my brain started itching.
Wouldn’t the approach there be to avoid mutating the same string (and thus reborrowing Map) in the first place? I’m likely missing something from the use case but why wouldn’t this work?
// Construct the fallback key separately
let fallback = format!("{k}-default");
// Use or_else() to avoid a second explicit `if map.contains_key(...)`
map.get_mut(k)
.or_else(|| map.get_mut(&fallback))
- css 2y agoYes, or use the entry api: https://doc.rust-lang.org/beta/std/collections/hash_map/enum.Entry.html https://doc.rust-lang.org/beta/std/collections/hash_map/enum...
- josephcsible 2y agoI see how that helps with the usual case of inserting a value under the original key if it wasn't there, but I don't see how it helps in this case of checking a different key entirely if it wasn't there.
- aoeusnth1 2y agoThis creates the fallback before knowing that you’ll need it.
- mrcsd 2y agoNot necessarily. Since the argument to `.or_else` is a function, the fallback value can be lazily evaluated.
- josephcsible 2y agoIt definitely needs get_mut(k) changed to get_mut(&k), but even after doing that, it still fails to compile, with an error similar to the one the original code gets.