Hey, i understand why i am getting the error: cannot borrow self.0 as mutable more than once, but is it even possible to make this code snippet cause a memory leak? I am writing Counter that if indexed mutably, it would create a new index of the key and assign it to zero. But how would i do that in this case? As i need two mutable refrences to the HashMap, one for inserting the element and one to return to the user! Here is the code:
I first tried returning the output of self.insert(), but this is of type Option<usize> and not Option<&mut usize>, so how can i do this? Can i bypass this somehow?
This is a limitation of the borrow checker, known as the problem case #3.
The code is safe in practice, it's just that the borrow checker picks one lifetime for the return type that spans the entire function body. It can be fudged with transmute of lifetimes, or structuring the code differently to do the lookup twice:
In the specific case of HashMap, you should just use entry() instead. It also avoids needing to hash the key up to 3 times, so it is much better for this case.