我正在使用Rust编写数据结构。它包含一个键值对的
Vec
。在向结构中插入内容时,我需要查找匹配的键并更新键和值(实际上是一个子指针)。代码看起来像这样,其中pivots
是对Vec<Pivot>
的ref mut
引用,而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
时。是否有更常见的方法执行更新或插入操作?