Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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))



I 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.


It 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.


This creates the fallback before knowing that you’ll need it.


Not necessarily. Since the argument to `.or_else` is a function, the fallback value can be lazily evaluated.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: