rust-lang / rust-lang/rust

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

Open
#141,880 2 comments 0 reactions 1 assignee View on GitHub

@xizheyin is already working on this.

Since Jun 3, 2025.

A-diagnostics T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.