【发布时间】:2017-11-20 15:13:04
【问题描述】:
我正在用 Rust 编写一个数据结构。它包含一个Vec 的键值对。插入结构时,我需要找到一个匹配的键并更新键和值(实际上是一个子指针)。代码看起来有点像这样,其中pivots 是ref mut 到Vec<Pivot> 而Pivot 只是一个包含两个字段的结构:
match pivots.iter_mut().find(|ref p| key <= p.min_key) { // first mutable borrow
Some(ref mut pivot) => {
// If there is one, insert into it and update the pivot key
pivot.min_key = key;
pivot.child.insert(key, value) // recursive call
},
// o/w, insert a new leaf at the end
None => pivots.push(Pivot /* ... */) // second mutable borrow
}
但是有一个问题。即使我没有在match 的第二个分支中使用可变迭代器,借用检查器仍抱怨我“不能一次多次将*pivots 借用为可变”。
这对我来说非常有意义,因为第一个借用仍在范围内,即使在 match 的这种情况下没有使用它。这有点不方便:一个更聪明的检查器肯定可以判断出借用是不重叠的。我在网上看到有人建议使用提前退货来避免这个问题,像这样:
match pivots.iter_mut().find(|ref p| key <= p.min_key) {
Some(ref mut pivot) => {
pivot.min_key = key;
pivot.child.insert(key, value);
return
},
None => ()
};
pivots.push(Pivot /* ... */)
但这似乎很难理解,尤其是当这意味着将这段代码分解为它自己的函数以允许return 时。是否有更惯用的方式来执行更新或插入操作?
【问题讨论】:
标签: rust borrow-checker