借阅检查员击败了我:
use std::collections::HashMap;
struct Cache {
cache: Vec<HashMap<String, String>>,
}
impl Cache {
fn get(&mut self, index: usize, key: String) -> String {
let mut cache = &mut self.cache[index];
match cache.get(&key) {
Some(r) => {
return r.clone();
}
None => {
let r = "foo".to_string(); // something smart here
cache.insert(key, r.clone());
return r;
}
}
}
}
我得到的是:
error[E0502]: cannot borrow `*cache` as mutable because it is also borrowed as immutable
--> src/main.rs:16:17
|
10 | match cache.get(&key) {
| ----- immutable borrow occurs here
...
16 | cache.insert(key, r.clone());
| ^^^^^ mutable borrow occurs here
...
19 | }
| - immutable borrow ends here
如何重写我的代码以便编译?
另一种方法是使用entry
接口。这种方法的唯一缺点是(当前)不使用BorrowFrom
该get
方法使用的基础结构,这使其灵活性降低了。在您的情况下,这不是问题,因为get
它拥有一个拥有的密钥。这样做的好处entry
是它只执行一次哈希查找,而使用则get
强制您执行两次查找。
use std::collections::HashMap;
struct Cache {
cache: Vec<HashMap<String, String>>,
}
impl Cache {
fn get(&mut self, index: usize, key: String) -> String {
self.cache[index]
.entry(key)
.or_insert_with(|| "foo".to_string())
.clone()
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句