Skip to content

Confusing lifetime error with closure #42758

Open
@dimbleby

Description

@dimbleby
struct Foo<'a> { foo: &'a str }

fn main() {
    let foo = Foo { foo: "foo" };
    let closure = |foo: Foo| foo;
    closure(foo);
}

Intuitively I don't quite see why this shouldn't compile, but:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
 --> <anon>:5:30
  |
5 |     let closure = |foo: Foo| foo;
  |                              ^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 5:19...
 --> <anon>:5:19
  |
5 |     let closure = |foo: Foo| foo;
  |                   ^^^^^^^^^^^^^^
note: ...so that expression is assignable (expected Foo<'_>, found Foo<'_>)
 --> <anon>:5:30
  |
5 |     let closure = |foo: Foo| foo;
  |                              ^^^
note: but, the lifetime must be valid for the call at 6:5...
 --> <anon>:6:5
  |
6 |     closure(foo);
  |     ^^^^^^^^^^^^
note: ...so type `Foo<'_>` of expression is valid during the expression
 --> <anon>:6:5
  |
6 |     closure(foo);
  |     ^^^^^^^^^^^^

Especially bewildering is that expected Foo<'_>, found Foo<'_>. Those look the same to me!

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-lifetimesArea: Lifetimes / regionsC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions