Trying to return reference from RwLock, “borrowed value does not live long enough” Error

后端 未结 1 773
感情败类
感情败类 2021-01-06 16:42

I\'ve been working on my first Rust project recently but have hit a snag. I am using a HashMap mapping Strings to AtomicUsize integers

相关标签:
1条回答
  • 2021-01-06 17:23

    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:

    1. Instead of Boxing 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.

    2. 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.

    0 讨论(0)
提交回复
热议问题