rust-lang / rust-lang/rust

Incorrect 'before the previous value is read' rustc warning on +=

Open
#159,371 2 comments 0 reactions 1 assignee View on GitHub

@Kokoro2336 is already working on this.

Since Jul 16, 2026.

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

Description

Code
fn sum_options(items: Vec<Option<u32>>) {
    let mut total = 0;
    for item in items {
        match item {
            Some(val) => total += val,
            None => total += 1,
        }
    }

    // println!("{}", total);
}
Current output
warning: value assigned to `total` is never read
 --> src/main.rs:5:26
  |
5 |             Some(val) => total += val,
  |                          ^^^^^^^^^^^^ this value is reassigned later and never used
6 |             None => total += 1,
  |                     ---------- `total` is overwritten here before the previous value is read
  |
  = note: `#[warn(unused_assignments)]` (part of `#[warn(unused)]`) on by default
Desired output
warning: value assigned to `total` is never read
 --> src/main.rs:5:26
  |
5 |             Some(val) => total += val,
  |                          ^^^^^^^^^^^^ this value is reassigned later and never used
6 |             None => total += 1,
  |                     ---------- this value is reassigned later and never used
  |
  = note: `#[warn(unused_assignments)]` (part of `#[warn(unused)]`) on by default
Rationale and extra context

"total is overwritten here before the previous value is read" makes no sense here: since I'm using +=, it's always read, although the variable is never used after the loop.

I'm not sure what the best error phrasing is here, but unless I'm missing something obvious the current wording is wrong.

Rust Version
$ rustc --version --verbose
rustc 1.96.0 (ac68faa20 2026-05-25)
binary: rustc
commit-hash: ac68faa20c58cbccd01ee7208bf3b6e93a7d7f96
commit-date: 2026-05-25
host: x86_64-unknown-linux-gnu
release: 1.96.0
LLVM version: 22.1.2

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.