rust-lang / rust-lang/rust

Incorrect "unused variable" warning

Open
#152,796 4 comments 1 reaction 1 assignee View on GitHub

@eggyal is already working on this.

Since Feb 18, 2026.

A-diagnostics A-lints C-bug D-incorrect L-unused_assignments L-unused_variables T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Code
pub struct Test {
    records: [TestRecord; 5],
}

#[derive(Clone,Copy)]
struct TestRecord {
    flag: bool,
}

impl TestRecord {
    pub fn new() -> TestRecord {
        TestRecord { flag: false }
    }
}

impl Test {
    pub fn new() -> Test {
        let records = [TestRecord::new(); 5];
        Test { records }
    }
}

fn main() {
    let mut e = Test::new();
    for mut r in e. records {
        r. flag = true;
        print!( "+" );
    }
    println!("");

    // The following equivalent gives no warning.
    e. records. iter_mut(). for_each( |r| { r. flag = true; print!( "*" ); } );
    println!("");
}
Current output
Compiling playground v0.0.1 (/playground)
warning: unused variable: `r`
  --> src/main.rs:26:9
   |
26 |     for mut r in e. records {
   |         ^^^^^ help: if this is intentional, prefix it with an underscore: `_r`
   |
   = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default

warning: `playground` (bin "playground") generated 1 warning (run `cargo fix --bin "playground" -p playground` to apply 1 suggestion)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.70s
     Running `target/debug/playground`
Desired output
Compiling playground v0.0.1 (/playground)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.75s
Rationale and extra context

No response

Other cases

Rust Version
rustc 1.93.1 (01f6ddf75 2026-02-11)
binary: rustc
commit-hash: 01f6ddf7588f42ae2d7eb0a2f21d44e8e96674cf
commit-date: 2026-02-11
host: x86_64-apple-darwin
release: 1.93.1
LLVM version: 21.1.8
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.