Comparing enums without data

Behold:

#[derive(PartialEq)]
enum MyEnum {
  Foo(String),
  Bar(String)
}

fn main() {
  let a = MyEnum::Foo("hello".to_string());
  let b = MyEnum::Foo("world".to_string());

  if a == b {
    println!("Equal!");
  } else {
    println!("Not equal!");
  }
}
Spoiler

It prints "Not equal!"

Not gonna lie, I didn't think Rust would compare the "inner" values out-of-the-box when deriving PartialEq, but it's really nice that it does that. With that said, I want it to do that, but I also have a section where I only want to compare the outer enum values. How does one do that (while retaining the current behavior)?

You can use mem::discriminant to get an identifier for the chosen option, or use pattern matching:

match (a,b) {
    (Bar(_), Bar(_)) => ...,
    (Foo(_), Foo(_)) => ...,
    _ => ...,
}
3 Likes

You can use std::mem::discriminant to get the discriminant of the enum case, which you can then compare.

let a = MyEnum::Foo("hello".to_string());
let b = MyEnum::Foo("world".to_string());

if std::mem::discriminant(a) == std::mem::discriminant(b) {
    println!("Equal!");
}

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.