借阅检查员打败了我:
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
如何重写我的代码以使其编译?