rust-lang / rust-lang/rust-clippy

Replace a single range in an `if let` by a boolean `if`

Open
#17,167 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

What it does

Matching against a single range pattern is equivalent to either an inequality or a range.contains() (ie two inequalities) or trivial. This lint would replace let range = ... in if let statements and let chains.

Advantage
  • Easier to read
  • Range pattern matches only work with integers and chars, while inequalities work more generally, so changing the type of the variable being matched would require a smaller change once this lint is applied
Drawbacks

In const contexts and when the range is either Range or RangeInclusive, the lint may not be an improvement:

  • Range::contains() uses PartialOrd so cannot be used in const contexts
  • if 3 <= x && x < 5 may be harder to read compared to if let 3..5 = x and if x is a complex expression then it requires a new binding to maintain the same semantics.
Example
if let 2.. = x && let ..10 = y && let 'a'..='z' = c {
    ...
}

Could be written as:

if x >= 2 && y < 10 && ('a'..='z').contains(&c) {
    ...
}
Comparison with existing lints

Instead of being a new lint, this could, or perhaps should, be part of redundant_pattern_matching. The lint equatable_if_let is also similar.

Additional Context

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.

Research direction

Start by reading the existing redundant_pattern_matching and equatable_if_let lints, since the issue proposes either extending one of them or adding a new lint. Compare the listed range-pattern cases and drawbacks, including const contexts and complex expressions; done means the chosen lint handles the intended cases without changing semantics.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.