Enum PartialEq where one variant doesn't match itself

Is there an easy way to have an enum with partialeq where one specific variant doesn't equal itself, like how NaN != NaN, or do I have to impl the entire partialeq with a match pattern for every variant to do this?

You can't customise the PartialEq derive macro from the standard library with any attributes. What you can look for is a crate that provides a more flexible derive macro for implementing PartialEq. I don't know such a crate. That being said, I personally wouldn't mind implementing it manually though.

Note that you don't have to match on every combination of variants. For example:

enum E {
    A,
    B,
    C(i32),
}

impl PartialEq for E {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (E::A, E::A) => false,
            (E::B, E::B) => true,
            (E::C(a), E::C(b)) => a == b,
            _ => false,
        }
    }
}

But NaN != NaN is a misguided design.

2 Likes

Can you add a marker field to the variant?

struct AlwaysUnequal;

impl PartialEq for AlwaysUnequal {
    fn eq(&self, other: &Self) -> bool {
       false
    }
}

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

Makes constructing the variant more verbose though.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.