Skip to content

Assigning to a for loop's element suggests replacing it with invalid code #155030

@ginnyTheCat

Description

@ginnyTheCat

Code

fn main() {
    for x in [1, 2, 3] {
        x += 1;
        println!("{x}");
    }
}

Current output

error[E0384]: cannot assign twice to immutable variable `x`
 --> src/main.rs:3:9
  |
2 |     for x in [1, 2, 3] {
  |         - first assignment to `x`
3 |         x += 1;
  |         ^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     for (mut x) x in [1, 2, 3] {
  |         +++++++

For more information about this error, try `rustc --explain E0384`.
error: could not compile `tmp` (bin "tmp") due to 1 previous error

Desired output

error[E0384]: cannot assign twice to immutable variable `x`
 --> src/main.rs:3:9
  |
2 |     for x in [1, 2, 3] {
  |         - first assignment to `x`
3 |         x += 1;
  |         ^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     for mut x in [1, 2, 3] {
  |         ++++

For more information about this error, try `rustc --explain E0384`.
error: could not compile `tmp` (bin "tmp") due to 1 previous error

Rationale and extra context

I noticed this at first since I thought the parens are unneeded, but even in that case it should only add (mut before and ) after, not (mut x) before, since (mut x) x is syntactically incorrect.

Other cases

Rust Version

rustc 1.96.0-nightly (900485642 2026-04-08)
binary: rustc
commit-hash: 900485642855f4729d926ecf24680a791f9293cf
commit-date: 2026-04-08
host: x86_64-unknown-linux-gnu
release: 1.96.0-nightly
LLVM version: 22.1.2

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
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions