rust-clippy
rust-clippy copied to clipboard
Unneeded casts in a comparison
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
}
`u16_value < b'a'`
That won't compile, types are incompatible.
@samueltardieu thanks, I was thinking about u8
, but later for some silly reason wrote u16
. My suggestion was only for compatible types of course.