rust-lang / rust-lang/rust-clippy

Unneeded casts in a comparison

Open
#12,343 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

Some comparisons are too obvious and just get in the way of understanding the code, and could be simplified.

Overall logic should check if the value grows in size (e.g. u8 -> i32), in which case if both values start as u8, or if one of the value type will be auto-detected (e.g. an integer without the type 0_i32), then the comparison should be simplified.

P.S. This was seen in the auto-converted Brotli C code, which generated tons of boilerplate code that Clippy should be able to catch. More lint suggestions forthcoming. See example for this lint.

Advantage
  • Cleaner, more readable, simpler code
Drawbacks

No response

Example
fn compare(u8_value: u8, u8_value2: u8) -> bool {
    (u8_value as i32) < b'a' as i32
    &&
    (u8_value as i32) == (u8_value2 as (i32))
    &&
    ((u8_value as i32) == 0_i32)    // note that we don't need specific integer type either
}

Could be written as:

fn compare(u8_value: u8, u8_value2: u8) -> bool {
    u8_value < b'a'
    &&
    u8_value == u8_value2
    &&
    u8_value == 0
}

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 Brotli comparison example in src/enc/static_dict.rs around line 570 and compare the casts with the intended simplified expressions in the issue. Identify the existing Clippy lint entry points for comparison analysis, then verify that the proposed lint handles widening casts and inferred integer literals without changing comparison behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.