I don't understand the error of the following code: Rust Playground
Why are lifetime incorrect?
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.
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:
get_or_load
with two keys, both of which are missing.HashMap
. All good so far.HashMap
, causing it to reallocate to make space.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.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.