Aurel
Aurel

Reputation: 479

How to get rid of "cannot return value referencing temporary value" error

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

Upvotes: 1

Views: 3618

Answers (1)

Aurel
Aurel

Reputation: 479

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!

Upvotes: 2

Related Questions