I'm solving a task from the Rust Book:
struct Cacher<T>
where
T: Fn(i32) -> i32,
{
calculation: T,
hm: HashMap<i32, i32>,
}
impl<T> Cacher<T>
where
T: Fn(i32) -> i32,
{
// ...
fn value(&mut self, arg: i32) -> i32 {
let v = self.hm.get(&arg); // borrowing returned Option<&V>
match v {
// matching owned value
Some(v) => *v, //return Copy'ied i32
None => {
let v2 = (self.calculation)(arg); // get result of closure
self.hm.insert(arg, v2); // memoize gotten value
v2 // return value
}
}
}
// ...
}
However, the compiler gives the following:
let v = self.hm.get(&arg);
--- immutable borrow occures here
Ok, I understand it, but the next message:
self.hm.insert(arg, v2);
^^^^^^^ mutable borrow occures here
How does this happens if I don't change the borrowed (v
) value in self.hm.insert(arg, v2);
?
I did a mutable borrow by changing let v
to let mut v
, but it didn't help: the compiler reports the same error.
How could I change my code to be able to insert a memoized value into the hash map?
Sorry for vague title, didn't find better description.