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
TradePairHandlecontains aRwLockReadGuard, 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.