if/else-if chain comparing the same two values with different operators
ID |
rust.maintainability.comparison_chain |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Control Flow |
Language |
Rust |
Description
Reports an if/else if chain that tests the same pair of values with two different comparison operators and ends in an else, which is a hand-written three-way comparison.
Rationale
The chain re-evaluates the same two operands on each branch, and nothing in it tells the compiler that the three cases are exhaustive and mutually exclusive - a later edit can add a fourth branch, drop the else, or flip one operator without any diagnostic. Ord::cmp returns the three-way answer once, and matching on Ordering makes the exhaustiveness the compiler’s job.
The following code illustrates the pattern detected by this rule:
pub fn greater_less(x: i32, y: i32) {
// FLAGGED: if/else-if chain comparing the same two values with different operators
if x > y {
println!("greater");
} else if x < y {
println!("less");
} else {
println!("equal");
}
}