Comparing tuple-like enum

I have below code where I'm comparing enum values.

#[derive(Eq, PartialEq)]
enum Fruit {
    Apple,
    Mango(i32),
    Banana,
}
fn main() {
    let a = Fruit::Mango(100);
    let b = Fruit::Mango(200);

    if a == b {
        println!("equal");
    } else {
        println!("not equal");
    }
}


Here i want to print equal when enum name is same. i.e. if enum is mango code should print equal irrespective of the i32 value inside it. what's the right way to do it?

Of you want to change the behavior of the == operator, you will need to write the PartialEq implementation manually instead of using the derived one.

If you don't want to change the behavior of the == operator itself for your enum type but instead just want to compare the enums in the described manner in this specific piece of code, then you don't need to change the PartialEq implementation. Either way, let's discuss how to implement the logic at hand.

A simple and efficient way to compare just the enum variant and no field data is by using std::mem::discriminant on both values and comparing the result. Make sure to test your code, to make sure it works as intended.

Without using the discriminant function, it's also possible to use pattern matching. You could e. g. match the expression (&a, &b) against an or-pattern (Apple, Apple) | (Mango(_), Mango(_)) | (Banana, Banana). Trying to do this can be educational to better learn how to use pattern matching, so you'll more easily be able to solve similar problems in the future, otherwise, it's probably the slightly inferior approach.

I'm on mobile right now, so I cannot write full code examples easily :slight_smile:

4 Likes

Thanks! I got my answer.Here I prefer pattern matching.

I wrote an example with core::mem::discriminant on playground :slight_smile:

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.