Skip to content

Lifetime elision is too greedy without explicit type declaration #39943

Closed
@dnsl48

Description

@dnsl48

In the next example the closure borrows the value for longer than it should do:

fn main () {
    let f = |y| { println!("{}", y); };
    let x = 4u8;
    f(&x);
}

Which causes compilation error:

error: `x` does not live long enough
 --> ./test.rs:5:1
  |
4 |     f(&x);
  |        - borrow occurs here
5 | }
  | ^ `x` dropped here while still borrowed
  |
  = note: values in a scope are dropped in the opposite order they are created

However, if we declare the argument type explicitly, it works just as expected:

fn main () {
    let f = |y: &u8| { println!("{}", y); };
    let x = 4u8;
    f(&x);
}

Not sure if that is a bug or expected behaviour. Neither could I find explanation of this effect in the documentation.

Meta

rustc --version --verbose:

rustc 1.17.0-nightly (24a70eb59 2017-02-09)
binary: rustc
commit-hash: 24a70eb598a76edb0941f628a87946b40f2a1c83
commit-date: 2017-02-09
host: x86_64-unknown-linux-gnu
release: 1.17.0-nightly
LLVM version: 3.9

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-inferenceArea: Type inferenceA-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.fixed-by-NLLBugs fixed, but only when NLL is enabled.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions