Hi all,
I am having an hard time understanding how to write a function that return a reference to an element inside a lock.
The code is quite simple:
pub struct Loop {
tx: Sender<r::Command>,
db: Arc<Mutex<sql::RawConnection>>,
}
impl LoopData for Loop {
fn get_db(&self) -> &sql::RawConnection {
&self.db.lock().unwrap()
}
}
But I am not sure I understand the error.
error[E0597]: borrowed value does not live long enough
--> src/lib.rs:62:10
|
62 | &self.db.lock().unwrap()
| ^^^^^^^^^^^^^^^^^^^^^^^ does not live long enough
63 | }
| - temporary value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 61:5...
--> src/lib.rs:61:5
|
61 | / fn get_db(&self) -> &sql::RawConnection {
62 | | &self.db.lock().unwrap()
63 | | }
| |_____^
The idea would be that loopdata.get_db
would take the lock and return a reference to the SQL connection, then when the reference goes out of scope the lock is released.
However, this doesn’t work but I am not quite sure I understood why.
Also here there is a playground version of the same code with the same problem: https://play.rust-lang.org/?gist=250a2d858beebb9eed7a5c14493ad0bf&version=stable
Can anybody point me out in the correct direction?