我尝试实现自己的类似物find_or_insert
方法看起来像这样:
use std::collections::HashMap;
pub struct SomeManager {
next: i32,
types: HashMap<i32, i32>,
}
impl SomeManager {
pub fn get_type<'a>(&'a mut self, k: i32) -> &'a i32 {
match self.types.get(&k) {
Some(ref x) => return *x,
None => {
self.types.insert(k, self.next);
self.next += 1;
return self.types.get(&k).unwrap();
}
}
}
}
fn main() {}
Error:
error[E0502]: cannot borrow `self.types` as mutable because it is also borrowed as immutable
--> src/main.rs:13:17
|
10 | match self.types.get(&k) {
| ---------- immutable borrow occurs here
...
13 | self.types.insert(k, self.next);
| ^^^^^^^^^^ mutable borrow occurs here
...
18 | }
| - immutable borrow ends here
我知道有一些标准方法可以实现此功能,但我希望此方法尽可能轻 - 它将被非常频繁地调用,并且几乎所有时间值都已经存在。
据我了解,当我们打电话时self.types.get
我们借用它的范围match声明,所以我们无法调用self.types.insert
这里。我尝试过将方法从None分支出match声明,但它也失败了。
我发现的唯一可行的解决方案需要调用get
twice:
pub fn get_type<'a>(&'a mut self, k: i32) -> &'a i32 {
let is_none = match self.types.get(&k) {
Some(ref x) => false,
None => true,
};
if is_none {
self.types.insert(k, self.next);
self.next += 1;
}
self.types.get(&k).unwrap()
}
我该如何解决这种情况?