Closed
Description
Even if this example may look silly, it's the result of the simplification of a more complex structure.
There should be no reason for these constructs not to compile, should it ?
use std::sync::RwLock;
fn main() {
let a = RwLock::new(RwLock::new(String::new()));
// Fails : a does not live long enough
let len = a.read().unwrap().read().unwrap().len();
// Fails : b does not live long enough
let len = { let b = a.read().unwrap(); b.read().unwrap().len() };
// Compiles
let len = { let b = a.read().unwrap(); let c = b.read().unwrap(); c.len() };
}
The full error message for the first construct does not really show what the problem might be:
<anon>:5:15: 5:32 error: borrowed value does not live long enough
<anon>:5 let len = a.read().unwrap().read().unwrap().len();
^~~~~~~~~~~~~~~~~
<anon>:5:5: 5:54 note: reference must be valid for the destruction scope surrounding statement at 5:4...
<anon>:5 let len = a.read().unwrap().read().unwrap().len();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:5:5: 5:54 note: ...but borrowed value is only valid for the statement at 5:4
<anon>:5 let len = a.read().unwrap().read().unwrap().len();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:5:5: 5:54 help: consider using a `let` binding to increase its lifetime
<anon>:5 let len = a.read().unwrap().read().unwrap().len();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error