I'm trying this (this is not a real code, just an example):
use std::collections::HashMap;
struct Foo {
kids : HashMap<i8, i8>
}
impl Foo {
pub fn update(&mut self) {
let keys = self.kids.keys().clone();
for k in keys {
self.mul(*k);
}
}
fn mul(&mut self, k: i8) {
self.kids.insert(k, k * k);
}
}
I'm getting:
error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
--> src/lib.rs:10:13
|
8 | let keys = self.kids.keys().clone();
| ---------------- immutable borrow occurs here
9 | for k in keys {
| ---- immutable borrow later used here
10 | self.mul(*k);
| ^^^^^^^^^^^^ mutable borrow occurs here
I think I understand why Rust complains, but what is the workaround? I need to get keys first and then modify the HashMap, going through it key by key.
I want to keep my mul() function, since in real code I do many more modifications there.