Skip to content

Use if let instead of if matches! #16660

@GideonBear

Description

@GideonBear

What it does

Warn against use of if matches! where it could be written as if let. I don't know in which cases this is or isn't safe.

This should probably be a pedantic lint (see drawbacks).

Advantage

  • More readable
  • Shorter
  • More idiomatic

Drawbacks

  • The pattern and the value are switched around, which might've been done intentionally for readability.

Example

enum E {
    A,
    B,
}

fn main() {
    let x = E::A;
    if matches!(x, E::A) {
        println!("It's an A");
    }
}

Could be written as:

enum E {
    A,
    B,
}

fn main() {
    let x = E::A;
    if let E::A = x {
        println!("It's an A");
    }
}

And:

enum E {
    A(u32),
    B,
}

fn main() {
    let x = E::A(1);
    if matches!(x, E::A(n) if n == 1) {
        println!("It's an A(1)");
    }
}

Could be written as:

enum E {
    A(u32),
    B,
}

fn main() {
    let x = E::A(1);
    if let E::A(n) = x && n == 1 {
        println!("It's an A(1)");
    }
}

(As long as let chains are available in the current Rust version)

Comparison with existing lints

No response

Additional Context

No response

Metadata

Metadata

Assignees

Labels

A-lintArea: New lints

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions