I have the following codes(playground):
use std::collections::HashMap;
fn get_immut(immut_dict: &HashMap<i32, Vec<i32>>, i: i32) -> &Vec<i32> {
&immut_dict[&i]
}
fn get_mut(mut_dict: &mut HashMap<i32, Vec<i32>>, i: i32) -> &Vec<i32> {
mut_dict.insert(i + 1, vec![i + 1]);
get_immut(mut_dict, i)
}
fn get_immut_twice(mut_dict: &mut HashMap<i32, Vec<i32>>) -> Vec<i32> {
let data1 = get_mut(mut_dict, 1);
let data2 = get_mut(mut_dict, 2);
data1.iter().zip(data2.iter()).map(|(x, y)| x + y).collect()
}
The complie error says that in get_immut_twice
I mutable borrow the argument mut_dict
twice.
I understand it in this way:
After I get let data1 = get_mut(mut_dict, 1)
, as long as data1
exits, mut_dict
is being mutable borrowed. If I call let data2 = get_mut(mut_dict, 2)
, the compile think I may change the existed data1
by calling the function get_mut
. So the error happened.
But I know that data1
would not be changed, what should I do?