rust-lang / rust-lang/rust

Compound assignment operator gives superfluous `warning: variable is assigned to, but never used`

Open
#122,447 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Code
fn main() {
    let mut foo = 1;
    foo += 1;
}
Current output
warning: variable `foo` is assigned to, but never used
 --> src/bin/test.rs:2:13
  |
2 |     let mut foo = 1;
  |             ^^^
  |
  = note: consider using `_foo` instead
  = note: `#[warn(unused_variables)]` on by default

warning: value assigned to `foo` is never read
 --> src/bin/test.rs:3:5
  |
3 |     foo += 1;
  |     ^^^
  |
  = help: maybe it is overwritten before being read?
  = note: `#[warn(unused_assignments)]` on by default
Desired output
warning: value assigned to `foo` is never read
 --> src/bin/test.rs:3:5
  |
3 |     foo += 1;
  |     ^^^
  |
  = help: maybe it is overwritten before being read?
  = note: `#[warn(unused_assignments)]` on by default
Rationale and extra context

If you change the 3rd line to foo = foo + 1, the first, superfluous warning goes away, and you are left with just the second, correct warning.

This bug comes up in issue https://github.com/rust-lang/rust/issues/63054, but is different; that one is about whether the last iteration of a loop should trigger the second warning. This bug just confused the issue there.

Other cases
fn main() {
    let mut foo = 1;
    foo = foo + 1;
}
Rust Version
rustc 1.76.0 (07dca489a 2024-02-04)
binary: rustc
commit-hash: 07dca489ac2d933c78d3c5158e3f43beefeb02ce
commit-date: 2024-02-04
host: x86_64-unknown-linux-gnu
release: 1.76.0
LLVM version: 17.0.6
Anything else?

If you change it to foo.add_assign(1), both warnings go away. I found that surprising since I thought += desugared into add_assign , so they would have the same output. Is that wrong?

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.

Research direction

Reproduce the warnings from src/bin/test.rs with rustc 1.76.0, comparing foo += 1, foo = foo + 1, and foo.add_assign(1). Investigate the compiler's handling of compound assignment and unused-variable diagnostics; done when the compound form reports only the unused-assignment warning shown in the desired output.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.