Skip to content

Incorrect "does not live long enough" with stdin().lock().lines() #33520

Closed
@LukasKalbertodt

Description

@LukasKalbertodt
fn main() {
    let foo: String = std::io::stdin().lock().lines().nth(0).unwrap().unwrap();
}

leads to

src\main.rs:14:23: 14:39 error: borrowed value does not live long enough                                               
src\main.rs:14     let foo: String = std::io::stdin().lock().lines().nth(1).unwrap().unwrap();                         
                                     ^~~~~~~~~~~~~~~~                                                                  
src\main.rs:14:5: 14:80 note: reference must be valid for the destruction scope surrounding statement at 14:4...       
src\main.rs:14     let foo: String = std::io::stdin().lock().lines().nth(1).unwrap().unwrap();                         
                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                         
src\main.rs:14:5: 14:80 note: ...but borrowed value is only valid for the statement at 14:4                            
src\main.rs:14     let foo: String = std::io::stdin().lock().lines().nth(1).unwrap().unwrap();                         
                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                         
src\main.rs:14:5: 14:80 help: consider using a `let` binding to increase its lifetime                                  
src\main.rs:14     let foo: String = std::io::stdin().lock().lines().nth(1).unwrap().unwrap();                         
                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                         

This doesn't make any sense since foo does not reference any temporary object (like Stdin or StdinLock). It's a String after all, as the optional type annotation shows.

Maybe related to #31439

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions