Incorrect lifetime closure and mutable

I don't understand the error of the following code: Rust Playground

Why are lifetime incorrect?

get takes a &mut reference to self that has to outlive the lifetime of the reference returned by get.

get_or_load then tries to call self.get repeatedly while storing the results, which means all those &mut references are being kept alive, all aliased (pointing to the same thing).

You can't have aliased &mut references. Consider returning Vec<Option<String>> so the lifetime used by self.get doesn't have to outlive a single call of the closure, or maybe altering the signature of get so it takes &self if you can.

1 Like

For performance reason I can't use any of thoses two options. Is there any other ways to solve this issue?

Imagine the following situation:

  1. I call get_or_load with two keys, both of which are missing.
  2. The first key is computed and added to the HashMap. All good so far.
  3. The second key is computed and added to the HashMap, causing it to reallocate to make space.
  4. The function now returns a collection containing (among other things) the first reference, which now points into deallocated memory.

Consider looping through it twice, making sure all the keys exist on the first pass, then using only &self methods to get references in the second pass.