Skip to content

Chaining unwrap(..) on temporaries raises a lifetime error #22921

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
elinorbgr opened this issue Mar 1, 2015 · 1 comment
Closed

Chaining unwrap(..) on temporaries raises a lifetime error #22921

elinorbgr opened this issue Mar 1, 2015 · 1 comment
Labels
A-type-system Area: Type system

Comments

@elinorbgr
Copy link
Contributor

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
@kmcallister kmcallister added the A-type-system Area: Type system label Mar 2, 2015
@arielb1
Copy link
Contributor

arielb1 commented Dec 28, 2015

duplicate of #22323.

@arielb1 arielb1 closed this as completed Dec 28, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-type-system Area: Type system
Projects
None yet
Development

No branches or pull requests

3 participants