Skip to content

compiler incorrectly suggest converting &x ->&mut x instead of &(mut x) when matching on a &T(T : Copy) #148467

@Morgane55440

Description

@Morgane55440

Code

fn myfun(s : &[u32]) {
    for &x in s {
        while x < 1000 {
            x *= 2;
        }
        println!("{x}")
    }
}

Current output

error[E0384]: cannot assign twice to immutable variable `x`
 --> src/lib.rs:6:13
  |
4 |     for &x in s {
  |          - first assignment to `x`
5 |         while x < 1000 {
6 |             x *= 2;
  |             ^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
4 |     for &mut x in s {
  |          +++
help: to modify the original value, take a borrow instead
  |
4 |     for &ref mut x in s {
  |          +++++++

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

Desired output

error[E0384]: cannot assign twice to immutable variable `x`
 --> src/lib.rs:6:13
  |
4 |     for &x in s {
  |          - first assignment to `x`
5 |         while x < 1000 {
6 |             x *= 2;
  |             ^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
4 |     for &(mut x) in s {
  |          ++++  +
help: you cannot modify the original value as it is behind a shared reference. use a different iterating method if you want to do so

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

Rationale and extra context

not sure if the second help i put is that useful, could be reworded or removed.

Other cases

Rust Version

rustc 1.91.0 (f8297e351 2025-10-28)
binary: rustc
commit-hash: f8297e351a40c1439a467bbbb6879088047f50b3
commit-date: 2025-10-28
host: x86_64-pc-windows-msvc
release: 1.91.0
LLVM version: 21.1.2

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsD-invalid-suggestionDiagnostics: A structured suggestion resulting in 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