【发布时间】:2014-06-18 13:53:16
【问题描述】:
我尝试实现类似于 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[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 两次:
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()
}
我该如何解决这种情况?
【问题讨论】:
标签: rust