Skip to content

Don't use PartialEq to check if an Option is None #9275

Closed
@lukaslueg

Description

@lukaslueg

What it does

I've seen people use foo == None or foo != None to check if Option<T>::is_none() / is_some(). This works fine as long as T is PartialEq, yet is unnecessary and may lead to surprising type errors later on in the programmer's life when the T is not PartialEq. The pattern most likely stems from other programming languages, where checking for null is expressed as foo is None or something similar. The programmer may not be aware that the comparison piggybacks on T: PartialEq, which is only practically useful in the Some-case.

Equality comparisons with Option::None should not be done in that way, and we can recommend Option::is_none() / is_some() or structural comparison, which are strictly more powerful and work for any Option<T> regardless if T: PartialEq

Lint Name

partialeq_to_none

Category

style, pedantic

Advantage

  • Intention is expressed more clearly
  • The triggering code is using the PartialEq trait on T in Option<T>, which the programmer is probably not aware of
  • We can replace the triggering code with a strictly more powerful alternative.

Drawbacks

No response

Example

pub fn foo(x: Option<u32>) -> &'static str {
    if x != None {
        "yay"
    } else {
        "nay"
    }
}

Could be written as:

pub fn foo(x: Option<u32>) -> &'static str {
    if x.is_some() {
        "yay"
    } else {
        "nay"
    }
}

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions