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?
This isn't something the compiler can prove statically. It also depends on the internals of hashmap - it would not remain valid if the map had to reallocate, for example.
With this particular exact code and API, since the .insert can actually invalidate the previously obtained reference to a HashMap item (e.g. in case the map is full and needs to re-allocate to grow), there’s really a bug here that needs to be addressed. The straightforward approach would be to decouple the mutation from the lookup, and do both mutations first, then both (immutable) lookups.