不能借用 `self` 作为不可变的,因为它也被借用为可变的

时间:2021-03-31 19:23:59

标签: rust

我有一个结构体来存储一个函数和一个现金映射:

struct Cacher<T>
where
    T: Fn(i32) -> i32,
{
    calculation: T,
    cached: HashMap<i32, i32>,
}

在这种方法中:

fn value(&mut self, arg: i32) -> i32 {
    *self
        .cached
        .entry(arg)
        .or_insert_with(|| (self.calculation)(arg))
}

我收到此错误:

error[E0502]: cannot borrow `self` as immutable because it is also borrowed as mutable
  --> src/caching.rs:29:29
   |
26 |           *self
   |  __________-
27 | |             .cached
   | |___________________- mutable borrow occurs here
28 |               .entry(arg)
29 |               .or_insert_with(|| (self.calculation)(arg))
   |                -------------- ^^  ---- second borrow occurs due to use of `self` in closure
   |                |              |
   |                |              immutable borrow occurs here
   |                mutable borrow later used by call

我知道 Rust 不喜欢我借用可变和不可变的东西,但是这段代码似乎没有什么不安全的。我怎么能告诉 Rust 我正在做的事情是安全的,或者我如何重构我的代码以使其工作? or_insert 方法将不起作用,因为它每次都计算函数调用。

0 个答案:

没有答案