Skip to content

[nll] borrows that must be valid for a free lifetime should explain why #52534

Closed
@nikomatsakis

Description

@nikomatsakis

Consider this example:

#![feature(nll)]
#![allow(warnings)]

fn foo(_: impl FnOnce(&u32) -> &u32) {
}

fn bar() {
    let x = 22;
    foo(|a| &x)
}

fn main() { }

This fails to compile -- and rightly so. The closure is supposed to return something with the same lifetime as its argument, but it returns &x. However, the error we get is quite confusing:

error[E0597]: `x` does not live long enough
  --> src/main.rs:9:9
   |
9  |     foo(|a| &x)
   |         ^^^^^^ borrowed value does not live long enough
10 | }
   | - borrowed value only lives until here
   |
   = note: borrowed value must be valid for the static lifetime...

this error arises because we infer (again, correctly) that if the &x expression returned a &'static u32, it would be suitable -- and hence it infers that the borrow must last for 'static (but it cannot).

Metadata

Metadata

Assignees

Labels

A-NLLArea: Non-lexical lifetimes (NLL)A-diagnosticsArea: Messages for errors, warnings, and lintsNLL-diagnosticsWorking towards the "diagnostic parity" goal

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions