Skip to content

Nonsensical suggestion when trying to move value in 'for' expression into closure #64559

Closed
@Aaron1011

Description

@Aaron1011
Member

This code:

fn main() {
    let orig = vec![true];
    for _val in orig {}
    let _closure = || orig;
}

gives the following error:

error[E0382]: use of moved value: `orig`
 --> src/main.rs:4:20
  |
2 |     let orig = vec![true];
  |         ---- move occurs because `orig` has type `std::vec::Vec<bool>`, which does not implement the `Copy` trait
3 |     for _val in orig {}
  |                 ----
  |                 |
  |                 value moved here
  |                 help: consider borrowing to avoid moving into the for loop: `&||`
4 |     let _closure = || orig;
  |                    ^^ ---- use occurs due to use in closure
  |                    |
  |                    value used here after move

error: aborting due to previous error

Rust suggests writing &|| to avoid borrowing. This suggestion is completely wrong - it is orig that should be borrowed (i.e. &orig). Attempting to follow the suggestion might lead a user to write let _closure = &|| orig;, which is still wrong.

Rust should properly suggest &orig in this scenario.

Activity

added
A-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`
C-bugCategory: This is a bug.
T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.
on Sep 17, 2019
added 2 commits that reference this issue on Sep 21, 2019

Rollup merge of rust-lang#64642 - cuviper:move-for-loop-snippet, r=va…

31b2f37

Rollup merge of rust-lang#64642 - cuviper:move-for-loop-snippet, r=va…

97ca073
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

    A-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @Aaron1011@jonas-schievink

      Issue actions

        Nonsensical suggestion when trying to move value in 'for' expression into closure · Issue #64559 · rust-lang/rust