These code can not compile. I try to understand the error: As long as v
is valid, my_dict
is mutable borrowed. So when I call my_dict.set_value(2, v)
, my_dict
is mutable borrowed at the same time immutable borrowed.
struct MyDict {
dict: HashMap<i32, Vec<f32>>,
}
impl MyDict {
fn new() -> Self {
MyDict { dict: HashMap::new() }
}
fn set_value(&mut self, k: i32, v: &Vec<f32>) {
let res = v.iter().map(|x| x + 1f32).collect();
self.dict.insert(k + 1, res);
}
fn get_inner_dict(&self) -> &HashMap<i32, Vec<f32>> {
&self.dict
}
}
fn main() {
let mut my_dict = MyDict::new();
my_dict.dict.insert(1, vec![1f32, 2., 3.]);
let v = &my_dict.get_inner_dict()[&1];
my_dict.set_value(2, v);
}
[E0502] Error: cannot borrow `my_dict` as mutable because it is also borrowed as immutable
โญโ[command_104:1:1]
โ
21 โ let v = &my_dict.get_inner_dict()[&1];
ยท โโโโโโโโโโโโโฌโโโโโโโโโโโ
ยท โฐโโโโโโโโโโโโโ immutable borrow occurs here
22 โ my_dict.set_value(2, v);
ยท โโโโโโโโโโโโฌโฌโโโโโโโโโโ
ยท โฐโโโโโโโโโโโโโ mutable borrow occurs here
ยท โ
ยท โฐโโโโโโโโโโโโ immutable borrow later used by call
โโโโโฏ
Maybe I can do this:
impl MyDict {
fn get_and_set(&mut self, k_get: i32, k_set: i32) {
let v = &self.dict[&k_get];
self.dict.insert(k_set, v.iter().map(|x| x + 1f32).collect());
}
}
But it may not seem brief? What am I missing?