Skip to content

Terrible error message when trying to use borrowed self in move closure #45634

Closed
@cramertj

Description

@cramertj

The code:

struct Foo {
    name: String,
}

impl Foo {
    fn foo(&self) -> Box<Fn()> {
        Box::new(move || println!("{}", self.name))
    }
}

Expected behavior: prints error that looks something like this:

self.name
^^^^ cannot use self in 'static move closure because `self` is borrowed

Actual behavior: prints this error message:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
 --> src/main.rs:8:9
  |
8 |         Box::new(move || println!("{}", self.name))
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 7:5...
 --> src/main.rs:7:5
  |
7 | /     fn foo(&self) -> Box<Fn()> {
8 | |         Box::new(move || println!("{}", self.name))
9 | |     }
  | |_____^
note: ...so that the type `[closure@src/main.rs:8:18: 8:51 self:&Foo]` will meet its required lifetime bounds
 --> src/main.rs:8:9
  |
8 |         Box::new(move || println!("{}", self.name))
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  = note: but, the lifetime must be valid for the static lifetime...
note: ...so that expression is assignable (expected std::boxed::Box<std::ops::Fn() + 'static>, found std::boxed::Box<std::ops::Fn()>)
 --> src/main.rs:8:9
  |
8 |         Box::new(move || println!("{}", self.name))
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.WG-diagnosticsWorking group: Diagnostics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions