Skip to content

compiler makes a suggestion that doesn't actually work (moving a statement outside a loop) #141880

@MatrixFrog

Description

@MatrixFrog

Code

use std::collections::HashMap;

fn main() {
    let name = String::from("foo");
    let mut maps = Vec::<HashMap<String, String>>::new();
    for m in maps.iter_mut() {
      let _entry = m.entry(name);
    }
    println!("{}", name);
}

Current output

error[E0382]: borrow of moved value: `name`
  --> src/main.rs:10:20
   |
5  |     let name = String::from("foo");
   |         ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
6  |     let mut maps = Vec::<HashMap<String, String>>::new();
7  |     for m in maps.iter_mut() {
   |     ------------------------ inside of this loop
8  |       let _entry = m.entry(name);
   |                            ---- value moved here, in previous iteration of loop
9  |     }
10 |     println!("{}", name);
   |                    ^^^^ value borrowed here after move
   |
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider moving the expression out of the loop so it is only moved once
   |
7  ~     let mut value = m.entry(name);
8  ~     for m in maps.iter_mut() {
9  ~       let _entry = value;
   |
help: consider cloning the value if the performance cost is acceptable
   |
8  |       let _entry = m.entry(name.clone());
   |                                ++++++++

For more information about this error, try `rustc --explain E0382`.

Desired output

The error is correct, but the first "help" suggestion is not helpful in this case: I can't move the `m.entry()` call outside of the loop because there is no `m` at that point.

Rationale and extra context

https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=e6a0dd9d486357dc798f72b0dc838971

Other cases

Rust Version

rustc 1.89.0-nightly (4d08223c0 2025-05-31)
binary: rustc
commit-hash: 4d08223c054cf5a56d9761ca925fd46ffebe7115
commit-date: 2025-05-31
host: x86_64-unknown-linux-gnu
release: 1.89.0-nightly
LLVM version: 20.1.5

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-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