Skip to content

unused_assignment triggered by closure even though value is used #141615

Open
@y86-dev

Description

@y86-dev

Code

fn main() {
    let mut a: Option<u32> = None;
    let mut cl = move || {
        a = Some(42);
        a.take().unwrap()
    };
    println!("{}", cl())
}

Current output

warning: value captured by `a` is never read
 --> src/main.rs:4:9
  |
4 |         a = Some(42);
  |         ^
  |
  = help: did you mean to capture by reference instead?
  = note: `#[warn(unused_assignments)]` on by default

Desired output

warning: value assigned to `a` is never read
 --> src/main.rs:2:13
  |
2 |     let mut a: Option<u32> = None;
  |             ^
  |
  = help: maybe it is overwritten before being read?
  = note: `#[warn(unused_assignments)]` on by default

Rationale and extra context

No response

Other cases

If the initial value is used, then the warning goes away, suggesting that it should warn on that instead:

fn main() {
    let mut a: Option<u32> = None;
    let mut cl = move || {
        let _ = a;
        a = Some(42);
        a.take().unwrap()
    };
    println!("{}", cl())
}

Rust Version

rustc 1.89.0-nightly (d97326eab 2025-05-15)
binary: rustc
commit-hash: d97326eabfc3b2c33abcb08d6bc117aefa697cb7
commit-date: 2025-05-15
host: x86_64-unknown-linux-gnu
release: 1.89.0-nightly
LLVM version: 20.1.4

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsA-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.D-imprecise-spansDiagnostics: spans don't point to exactly the erroneous codeL-unused_assignmentsLint: unused_assignmentsT-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