如何说服借用检查器允许我缓存值? [英] How can I convince the borrow checker to allow me to cache values?
本文介绍了如何说服借用检查器允许我缓存值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
借阅检查员打败了我:
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
如何重写我的代码以使其能够编译?
How can I rewrite my code so that it compiles?
推荐答案
另一种方法是使用 entry
接口.这种方法的唯一缺点是它(目前)不使用 get
方法使用的 BorrowFrom
基础结构,这使得它不太灵活.在您的情况下,这不是问题,因为 get
需要一个拥有的密钥.entry
的优点是它只进行一次哈希查找,而使用 get
会强制您进行两次查找.
Another approach is to use the entry
interface. The only downside with this approach is that it (currently) doesn't use the BorrowFrom
infrastructure that the get
method uses, which makes it less flexible. In your case, that isn't a problem since get
takes an owned key. The advantage of entry
is that it only does one hash lookup, whereas using get
forces you to do two lookups.
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()
}
}
这篇关于如何说服借用检查器允许我缓存值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文