1

I'm trying to implement a method that returns a RwLockReadGuard of a struct contained into a HashMap (itself in a RwLock).

The function below:

pub fn get_pair<'a>(&self, name: &str) -> Option<TradePairHandle> { if let Ok(ref pair) = self.pairs.read() { if let Some(p) = pair.get(name) { if let Ok(r) = p.read() { Some(TradePairHandle::new(r)) } else { None } } else { None } } else { None } } 

raise the following compilation error:

error[E0515]: cannot return value referencing temporary value --> src/lib.rs:76:21 | 73 | if let Ok(ref pair) = self.pairs.read() { | ----------------- temporary value created here ... 76 | Some(TradePairHandle::new(r)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value 

referencing data owned by the current function

How to do this the correct way?

There is the full Rust playground

9
  • Does this answer your question? Is there any way to return a reference to a variable created in a function? Commented Aug 20, 2020 at 9:18
  • I m' afraid not, in my example the function don't return a reference Commented Aug 20, 2020 at 9:21
  • Your function does return a reference, since TradePairHandle contains a RwLockReadGuard, which in turn holds a reference. However, it's not entirely accurate that the value that reference is pointing to is "created" inside your function. Commented Aug 20, 2020 at 9:24
  • The problem is rather that the outer lock, the one you grab in the first line of the function, will be released when returning from the function, so any reference you obtain from inside that lock will become invalid at that point. Commented Aug 20, 2020 at 9:26
  • 1
    @SvenMarnach ok, There it is: stackoverflow.com/questions/63523566/… Commented Aug 21, 2020 at 13:12

1 Answer 1

2

Thanks to Sven Marnach, I tried a different approach with owning_ref crate. Now the method get_pair looks like this:

pub fn get_pair<'a, 'me: 'a>( &'me self, name: &str, ) -> RwLockReadGuardRef<'a, TradePairHashMap, Arc<RwLock<TradePair>>> { RwLockReadGuardRef::new(self.pairs.read().unwrap()).map(|pairs| pairs.get(name).unwrap()) } 

And compile without errors. Thanks again!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.