4

Learning Rust I happen to need to compare variants inside nested enums. Considering following enums how do I compare actual variants of instantinated BuffTurget?

enum Attribute {
  Strength,
  Agility,
  Intellect,
}

enum Parameter {
    Health,
    Mana,
}

enum BuffTarget {
    Attribute(Attribute),
    Parameter(Parameter),
}

Searching the web led me to the `discriminant and particularly to comparison function like this:

fn variant_eq<T>(a: &T, b: &T) -> bool {
    std::mem::discriminant(a) == std::mem::discriminant(b)
}

Unfortunately this function is not working in my case:

#[test]
fn variant_check_is_working() {
    let str = BuffTarget::Attribute(Attribute::Strength);
    let int = BuffTarget::Attribute(Attribute::Intellect);
    assert_eq!(variant_eq(&str, &int), false);
}

// Output:

// thread 'tests::variant_check' panicked at 'assertion failed: `(left == right)`
// left: `true`,
// right: `false`', src/lib.rs:11:9

Ideally I would like my code to be something like this, using if let:

let type_1 = get_variant(BuffTarget::Attribute(Attribute::Strength));
let type_2 = get_variant(BuffTarget::Attribute(Attribute::Intellect));

if let type_1 = type_2 {  
    println!("Damn it!") 
} else { println!("Success!!!") }
SS_Rebelious
  • 1,274
  • 2
  • 19
  • 35
  • 1
    Possible duplicate of [How to implement PartialEq for an enum?](https://stackoverflow.com/questions/36297412/how-to-implement-partialeq-for-an-enum) – jonny Mar 07 '19 at 17:21

1 Answers1

7

Found suitable solution in this answer. Use #[derive(PartialEq)] for the enums to compare them with ==: enum_1 == enum_2.

#[derive(PartialEq)]
enum Attribute {
  Strength,
  Agility,
  Intellect,
}

#[derive(PartialEq)]
enum Parameter {
    Health,
    Mana,
}

#[derive(PartialEq)]
enum BuffTarget {
    Attribute(Attribute),
    Parameter(Parameter),
}

let type_1 = BuffTarget::Attribute(Attribute::Strength));
let type_2 = BuffTarget::Attribute(Attribute::Intellect));

assert_eq!((type_1 == type_2), false);
SS_Rebelious
  • 1,274
  • 2
  • 19
  • 35