Skip to content

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

Closed
@Aaron1011

Description

@Aaron1011

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.

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

    No branches or pull requests

    Issue actions