【发布时间】:2022-01-14 23:53:05
【问题描述】:
我正在尝试编写一段代码来检查一个条目是否在缓存中,以及它是否不产生值。
问题是为了产生值,我想传递缓存,因为生产者可能想要使用其他值,或者可能想要插入自己的值。
当前代码如下:
#[derive(Default)]
pub struct R {}
#[derive(Hash, PartialEq, Eq, Clone)]
pub struct Mutation {}
fn create_mutations(s: &Mutation) -> Vec<Mutation> {
todo!();
}
fn expand(v1: &mut R, v2: &R) {
todo!();
}
pub fn rec_fn(cache: &mut HashMap<Mutation, R>, s: &Mutation) -> R {
let mut results: R = R::default();
let mutations = create_mutations(s);
for mutation in mutations {
if cache.get(&mutation).is_none() {
let r = rec_fn(cache, &mutation);
cache.insert(mutation.clone(), r);
}
let mutations_of_mutation = &cache[&mutation];
expand(&mut results, mutations_of_mutation);
}
results
}
我遇到的问题是我的Mutation 块必须是Clone。
我想知道我是否可以以不同的方式编写缓存获取和插入的块。
一种看起来很有希望但被借用检查器关闭的方法是:
pub fn rec_fn(cache: &mut HashMap<Mutation, R>, s: &Mutation) -> R {
let mut results: R = R::default();
let mutations = create_mutations(s);
for mutation in mutations {
let mutations_of_mutation = cache.entry(mutation).or_insert_with_key(|m| rec_fn(cache, m));
expand(&mut results, mutations_of_mutation);
}
results
}
出现错误:
error[E0500]: closure requires unique access to `*cache` but it is already borrowed
--> src/main.rs:97:78
|
97 | let mutations_of_mutation = cache.entry(mutation).or_insert_with_key(|m| rec_fn(cache, m));
| --------------------- ------------------ ^^^ ----- second borrow occurs due to use of `*cache` in closure
| | | |
| | | closure construction occurs here
| | first borrow later used by call
| borrow occurs here
我明白为什么会这样。但是有没有办法在没有克隆mutation的情况下写这个?
【问题讨论】: