Skip to content

Suggestion to move expression out of loop triggers in cases that are not applicable #149861

@estebank

Description

@estebank

When given

    for i in 0..20 {
        // let results = Arc::clone(&results);
        pool.execute(move || {
            let mut r = results.lock().unwrap();
            r.push(i);
        });
    }

we currently emit


error[E0382]: use of moved value: `results`
  --> src/main.rs:30:22
   |
22 |     let results = Arc::new(Mutex::new(Vec::new()));
   |         ------- move occurs because `results` has type `Arc<std::sync::Mutex<Vec<i32>>>`, which does not implement the `Copy` trait
...
28 |     for i in 0..20 {
   |     -------------- inside of this loop
29 |         // let results = Arc::clone(&results);
30 |         pool.execute(move || {
   |                      ^^^^^^^ value moved into closure here, in previous iteration of loop
31 |             let mut r = results.lock().unwrap();
   |                         ------- use occurs due to use in closure
   |
help: consider moving the expression out of the loop so it is only moved once
   |
28 ~     let mut value = results.lock();
29 ~     for i in 0..20 {
30 |         // let results = Arc::clone(&results);
31 |         pool.execute(move || {
32 ~             let mut r = value.unwrap();
   |
help: consider cloning the value before moving it into the closure
   |
30 ~         let value = results.clone();
31 ~         pool.execute(move || {
32 ~             let mut r = value.lock().unwrap();
   |

The first suggestion was introduced in #121652, but it shouldn't apply for cases like this one, so we should improve the gating of that suggestion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.D-verboseDiagnostics: Too much output caused by a single piece of incorrect code.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