rust-lang / rust-lang/rust-clippy

lint if/else to match enum variant if we could use match

Open
#9,051 0 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

lint if-else chains on enums that could be more compact and idiomatic matches.
We might want to bail out of the if/else also includes conditions that are unrelated to the enum variant (if x = 2 && E == E::A)

#[derive(Eq, PartialEq)]
enum E {
    A,
    B,
    C
}


fn fun(e: &E) -> i32 {
    if e == &E::A {
        1
    } else if e == &E::B {
        2
    } else {
        3
    }
}

// suggest instead:
fn fun2(e: &E) -> i32 {
    match e {
        E::A => 1,
        E::B => 2,
        _ => 3,
    }
}

There might be other subtle differences regarding lifetimes/peformance or whatever that I'm not aware of right now

Lint Name

?

Category

style

Advantage

I think the match statements are more compact and idiomatic and easier to understand

Drawbacks

No response

Example
fn fun(e: &E) -> i32 {
    if e == &E::A {
        1
    } else if e == &E::B {
        2
    } else {
        3
    }
}

Could be written as:

fn fun2(e: &E) -> i32 {
    match e {
        E::A => 1,
        E::B => 2,
        _ => 3,
    }
}

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

The issue names no source files, tests, or entry points. Start from the Rust examples and proposed style category, then establish the lint's exact matching scope, including unrelated conditions, and define how accepted and rejected cases will be tested; done means the behavior and limitations are agreed.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.