rust-lang / rust-lang/rust-clippy

Remove unnecessary `if` statement when results can be determined at compile time

Open
#11,378 2 comments 0 reactions 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

If an if else expression only contains static types, such as i8s and u32s, not variables, then it's likely that one branch can be totally removed without the "correctness" of the code changing.

A Reddit thread (Archive.org link) demonstrated this by putting an if else inside another if, which was evaluated correctly.

I'm not exactly sure whether this lint should capture:

  • Just freestanding if statements that can be determined ahead (comparing two integers)
  • if else statements (which most definitely yield a value) inside another if statement (like the Reddit example)
Advantage
  • Remove unnecessary code branches.
  • Makes the code easier to read.
Drawbacks

Someone might intend to later "fill out" the other branches, which is why this is limiting it to if-else expressions in another if statement, as opposed to freestanding if statements might make more sense, the former is usually an unintended, while the latter could be intended to be added to.

Example
let a = 13;
if if a == 13 { 10 } else { 0 } > 5 { // <- nested if-else
    println!("This will be printed");
}

Could be written as this (if we're just looking for nested ones):

let a = 13;
if 10 > 5 { // <- inner if-else removed, however the outer if-statement, which *could* be removed, isn't
    println!("This will be printed");
}

Or

let a = 13;
println!("This will be printed"); // <- if removed, but most likely more "annoying"

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 with the issue's nested if-else examples and determine whether the proposed lint should cover only nested expressions or also freestanding compile-time conditions. Resolve the stated scope and intent concerns before identifying the implementation entry point; done means the lint behavior and boundaries are clearly decided.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.