Skip to content

comparison_chain: don't warn unless all branches are used #14624

Open
@tgross35

Description

@tgross35

Summary

comparison_chain probably doesn't need to be raised unless all three branches are used, i.e. if there is a final else condition. With only two branches, the change doesn't seem to add any clarity.

Lint Name

comparison_chain

Reproducer

Link: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&gist=256e04cad4d4ef0d7cbdaeaf91309aad

I tried this code:

pub fn foo(a: i32) -> i32 {
    if a < 0 {
        return 5;
    } else if a == 0 {
        return 10;
    }

    unimplemented!();
}

I saw this happen:

warning: `if` chain can be rewritten with `match`
 --> src/lib.rs:4:5
  |
4 | /     if a < 0 {
5 | |         return 5;
6 | |     } else if a == 0 {
7 | |         return 10;
8 | |     }
  | |_____^ help: consider rewriting the `if` chain with `match`: `match a.cmp(&0) {...}`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#comparison_chain
note: the lint level is defined here
 --> src/lib.rs:1:9
  |
1 | #![warn(clippy::comparison_chain)]
  |    

Which would be

    match a.cmp(&0) {
        Ordering::Less => return 5,
        Ordering::Equal => return 10,
        Ordering::Greater => {}
    }

I expected to see this happen:

No output

Version

1.88.0-nightly
(2025-04-07 e643f59f6da3a84f43e7)

Additional Labels

@rustbot label +L-suggestion

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesI-false-positiveIssue: The lint was triggered on code it shouldn't haveL-suggestionLint: Improving, adding or fixing lint suggestions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions