rust-lang / rust-lang/rust-clippy

`if let` binding used in same expression

Open
#16,338 2 comments 4 reactions 1 assignee View on GitHub

@DeepenNehra is already working on this.

Since Jan 6, 2026.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

It detects when a variable binding created by an if let pattern is used in "the same" expression that the pattern is matching against

Advantage
  • It's less confusing, as one might think the code will be rejected by the compiler (because the binding is used before being assigned a value), but it isn't
Drawbacks
  • Less concise code
Example

(very contrived)

fn f(b: u8) -> u8 {
    if let Some(n) = std::num::NonZeroU8::new(b)
        && n.get() % 2 == 1
    {
        n.get() / 2
    } else {
        0
    }
}

Could be written as:

fn f(b: u8) -> u8 {
    if let Some(n) = std::num::NonZeroU8::new(b) {
        let n = n.get();
        if n % 2 == 1 {
            return n / 2;
        }
    }
    0
}
Comparison with existing lints

It seems there's no similar lint

Additional Context

I got the idea here, which is real code that was confusing to me

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.