I\'ve been working on my first Rust project recently but have hit a snag. I am using a HashMap
mapping String
s to AtomicUsize
integers
You're correct that you can't return a reference to something which outlives the MutexGuard
, because that would lead to a possibly dangling pointer.
Wrapping the contents in a Box
won't help, though! A Box
is an owned pointer and apart from the redirection behaves like the contained value as far as reference lifetime goes. After all, if you returned a reference to it, someone else might remove it from the HashMap
and de-allocate it.
Depending on what you want to do with the reference, I can think of a couple of options:
Instead of Box
ing the values, wrap them in Arc
. You would clone the Arc
when taking from the HashMap
, and multiple references can live at the same time.
You could also return the MutexGuard
along with the reference; see this question, which would work well if you just want to operate on the value and then drop the reference relatively soon. This would keep the mutex held until you're finished with it.