Skip to content

FP single_match_else (lifetimes) #14925

@matthiaskrgr

Description

@matthiaskrgr

Summary

.

Lint Name

single_match_else

Reproducer

I tried this code:

#![warn(clippy::single_match_else)]
use std::marker::PhantomData;

struct Inv<'a>(PhantomData<*mut &'a ()>);

impl PartialEq for Inv<'static> {
    fn eq(&self, _: &Inv<'static>) -> bool {
        true
    }
}

impl<'a> Inv<'a> {
    const NOT_STATIC: Option<Self> = None;
}

fn foo<'a>(x: Option<Inv<'a>>) {
    match x {
        Inv::<'a>::NOT_STATIC => (),
        Some(_) => panic!()
    }
}

fn main() {
    foo(None)
}

I saw this happen:

warning: you seem to be trying to use `match` for an equality check. Consider using `if`
  --> src/main.rs:17:5
   |
17 | /     match x {
18 | |         Inv::<'a>::NOT_STATIC => (),
19 | |         Some(_) => panic!()
20 | |     }
   | |_____^ help: try: `if x == Inv::<'a>::NOT_STATIC { () } else { panic!() }`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_match_else
note: the lint level is defined here
  --> src/main.rs:1:9
   |
1  | #![warn(clippy::single_match_else)]
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^

suggested code:

#![warn(clippy::single_match_else)]
use std::marker::PhantomData;

struct Inv<'a>(PhantomData<*mut &'a ()>);

impl PartialEq for Inv<'static> {
    fn eq(&self, _: &Inv<'static>) -> bool {
        true
    }
}

impl<'a> Inv<'a> {
    const NOT_STATIC: Option<Self> = None;
}

fn foo<'a>(x: Option<Inv<'a>>) {
    if x == Inv::<'a>::NOT_STATIC { () } else { panic!() }
}

fn main() {
    foo(None)
}

does not compile:

error: lifetime may not live long enough
  --> src/main.rs:17:8
   |
16 | fn foo<'a>(x: Option<Inv<'a>>) {
   |        -- lifetime `'a` defined here
17 |     if x == Inv::<'a>::NOT_STATIC { () } else { panic!() }
   |        ^^^^^^^^^^^^^^^^^^^^^^^^^^ requires that `'a` must outlive `'static`

error: could not compile `f` (bin "f") due to 1 p

Version


Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions