rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

Suggest using `==` instead of `matches!`

Open emilk opened this issue 1 year ago • 5 comments

What it does

Looks for unnecessary uses of matches! that can be replaced with == or !=

Advantage

Using matches! can produce unnecessarily complex code. When negated, you also get the "double-bang" confusion of !matches!(…), where tje twp ! means different things.

Drawbacks

No response

Example

if !matches!(value, Enum::Variant) { … 

Could be written as:

if value != Enum::Variant { … 

emilk avatar Apr 24 '25 14:04 emilk

FWIW: Notice that value != Enum::Variant requires Enum: PartialEq, while matches! does not; this also means Enum<T: PartialEq>, even if Enum::Variant does not carry a T. We have a warn-by-default lint wrt value == None in place so people don't fall into this specific pattern. IMHO its not advisable to teach people to do by-value comparison if structural comparison is what they need.

lukaslueg avatar Apr 25 '25 07:04 lukaslueg

Yes, we should of course only suggest using == or != for types that implement PartialEq

emilk avatar Apr 25 '25 09:04 emilk

@rustbot claim

NullSpaceBoy avatar May 15 '25 16:05 NullSpaceBoy

I don't think this lint should be warn-by-default, this should probably be in the pedantic category.

See discussion on this PR, which tried to replace some matches! with ==, but it was somewhat controversial: https://github.com/rust-lang/rust/pull/149933. I agree with the points mentioned there

nik-rev avatar Apr 04 '26 00:04 nik-rev

Opened #17018.

GuillaumeGomez avatar May 16 '26 00:05 GuillaumeGomez