Skip to content

Implicit return leads to "does not live long enough" error. #31439

Closed
@gyscos

Description

@gyscos

Here is a simple function that tries to read all lines from input:

use std::io::{self,BufRead};

fn lines() -> Vec<String> {
    let stdin = io::stdin();
    let handle = stdin.lock();

    handle.lines().map(|line| line.unwrap()).collect()
}

fn main() {
}

As shown here, attempting to compile it (on stable 1.6, beta or nightly) gives a lifetime error:

<anon>:5:18: 5:23 error: `stdin` does not live long enough
<anon>:5     let handle = stdin.lock();
                          ^~~~~
<anon>:3:27: 8:2 note: reference must be valid for the destruction scope surrounding block at 3:26...
<anon>:3 fn lines() -> Vec<String> {
<anon>:4     let stdin = io::stdin();
<anon>:5     let handle = stdin.lock();
<anon>:6 
<anon>:7     handle.lines().map(|line| line.unwrap()).collect()
<anon>:8 }
<anon>:4:29: 8:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 4:28
<anon>:4     let stdin = io::stdin();
<anon>:5     let handle = stdin.lock();
<anon>:6 
<anon>:7     handle.lines().map(|line| line.unwrap()).collect()
<anon>:8 }

Making the return explicit fixes this:

use std::io::{self,BufRead};

fn lines() -> Vec<String> {
    let stdin = io::stdin();
    let handle = stdin.lock();

    return handle.lines().map(|line| line.unwrap()).collect();
}

fn main() {
}

Is this the expected behavior? I would have thought explicit and implicit returns would give the same result...

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regionsT-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions