I'm confused about the best way to write the following very common kind of code:
let old_best = best_by_pos[y][x].as_ref();
if old_best.is_none() || &new_cost < old_best.unwrap() {
best_by_pos[y][x] = Some(new_cost.clone());
}
This is just a code sample, but it illustrates the problem.
best_by_pos is a Vec<Vec<Option<BigInt>>>; when we find a new possibility for the best cost at that point, we want to (a) check if the new cost is better than the old cost, and (b) if it is, update the vector.
The problem is that old_best borrows best_by_pos immutably, and that borrow persists until the end of the scope. This prevents the mutation inside the if block. Ideally I'd like to free up old_best immediately after the test but it's not clear how to do that.
There is a very ugly way to do it -- make a deeper scope which does the test and exposes a boolean, then doing a conditional on that. This is functional but unpleasant.
Alternately, I can make a helper method which does the comparison (and frees up its borrows when it terminates), which looks cleaner, but still feels bloated.
Is there a cleaner way to achieve this?