我对编写以下非常常见的代码的最佳方法感到困惑:
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());
}
这只是一个代码示例,但它说明了问题。
best_by_pos
是一个Vec<Vec<Option<BigInt>>>
;当我们在这一点上找到最佳成本的新可能性时,我们要(a(检查新成本是否优于旧成本,(b(如果是,则更新向量。
问题在于old_best
借用best_by_pos
不变,并且借用一直持续到范围结束。这可以防止 if 块内的突变。理想情况下,我想在测试后立即释放old_best
,但不清楚如何做到这一点。
有一种非常丑陋的方法 - 做一个更深的范围来进行测试并公开一个布尔值,然后做一个条件。这是功能性的,但令人不快。
或者,我可以制作一个辅助方法来进行比较(并在终止时释放其借用(,它看起来更干净,但仍然感觉臃肿。
有没有更清洁的方法来实现这一点?
你可以old_best
成为对向量的可变引用,并在赋值中写入它。这也允许您避免再次为向量编制索引:
let old_best = &mut best_by_pos[y][x];
if old_best.is_none() || &new_cost < old_best.as_ref().unwrap() {
*old_best = Some(new_cost.clone());
}
如果你必须留在Vec
,这样的事情避免了任何明确的unwrap
s:
let slot = &mut best_by_pos[y][x];
let is_better = slot.as_ref().map_or(true, |old_cost| &new_cost < old_cost);
if is_better {
*slot = Some(new_cost.clone());
}
这仍然在向量中保留了一个可变的借用,因此您需要将其包装在作用域中。
另一种可能性是一些不太常见的模式语法:
match best_by_pos[y][x] {
ref mut entry @ None => *entry = Some(new_cost.clone()),
Some(ref mut entry) => {
if &new_cost < entry {
*entry = new_cost.clone();
}
}
}
猜测,根据向量内Option
的使用情况,我鼓励您不要使用Vec
。相反,HashMap
可以更好地表示稀疏数组的概念。此外,您还可以使用入口 API:
use std::collections::HashMap;
use std::collections::hash_map::Entry;
let mut best_by_pos: HashMap<(usize, usize), BigInt> = Default::default();
match best_by_pos.entry((x, y)) {
Entry::Vacant(e) => {
e.insert(new_cost.clone());
}
Entry::Occupied(mut e) => {
if &new_cost < e.get() {
e.insert(new_cost.clone());
}
}
}
Option<T>
实现Ord
所有类型的T
,实现Ord
,其方式是None
对于任何v
都小于Some(v)
。您可以像这样编写代码:
if best_by_pos[y][x].is_none() || Some(&new_cost) < best_by_pos[y][x].as_ref() {
best_by_pos[y][x] = Some(new_cost.clone());
}
考虑到间答,也可以写成
let cost = &mut best_by_pos[y][x];
if cost.is_none() || Some(&new_cost) < cost.as_ref() {
*cost = Some(new_cost.clone());
}
如果您使用其他Entry
方法,and_modify
和or_insert
,HashMap
可以非常简洁
use std::collections::HashMap;
fn main() {
let mut best_pos: HashMap<(usize, usize), f64> = Default::default();
let newprice = 60.0;
best_pos
.entry((1, 2))
.and_modify(|e| *e = e.min(newprice))
.or_insert(newprice);
}