Skip to content

Compiler does not suggest move when it would be appropriate #56093

@grantslatton

Description

@grantslatton

This snippet does not compile with the following error:

pub fn main() {
    |i: u32| { || i };
}

error[E0597]: `i` does not live long enough
 --> src/main.rs:2:19
  |
2 |     |i: u32| { || i };
  |                -- ^ - borrowed value dropped before borrower
  |                |  |
  |                |  borrowed value does not live long enough
  |                capture occurs here
  |
  = note: values in a scope are dropped in the opposite order they are created

https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=2aa8b97e68b9eba4c1b7c0d3f627c386

But adding a move fixes it:

pub fn main() {
    |i: u32| { move || i };
}

I believe the compiler tries to suggest move where appropriate, and it seems that this case has been missed.

Activity

grantslatton

grantslatton commented on Dec 7, 2018

@grantslatton
Author

With Rust 2018 this now provides the correct error message:

error[E0373]: closure may outlive the current function, but it borrows `i`, which is owned by the current function
 --> src/main.rs:2:16
  |
2 |     |i: u32| { || i };
  |                ^^ - `i` is borrowed here
  |                |
  |                may outlive borrowed value `i`
  |
note: closure is returned here
 --> src/main.rs:2:16
  |
2 |     |i: u32| { || i };
  |                ^^^^
help: to force the closure to take ownership of `i` (and any other referenced variables), use the `move` keyword
  |
2 |     |i: u32| { move || i };
  |                ^^^^^^^
added a commit that references this issue on Mar 11, 2019
65cb35a
added 3 commits that reference this issue on Apr 22, 2019
bf0ea60
c21fbfe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    fixed-by-NLLBugs fixed, but only when NLL is enabled.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @grantslatton@matthewjasper

      Issue actions

        Compiler does not suggest `move` when it would be appropriate · Issue #56093 · rust-lang/rust