#[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 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!");
}