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");
    }
}

Remediation

Compare once and match on the result: match a.cmp(&b) { Ordering::Greater ⇒ …​, Ordering::Less ⇒ …​, Ordering::Equal ⇒ …​ }, with use std::cmp::Ordering;. For a partially ordered type such as f64, use partial_cmp and handle the None case.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved