在Rust中比较嵌套枚举变体

4

在学习Rust时,我需要比较嵌套的枚举内部的变量。考虑以下枚举类型,如何比较实例化的BuffTurget的实际变量?

enum Attribute {
  Strength,
  Agility,
  Intellect,
}

enum Parameter {
    Health,
    Mana,
}

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

在搜索网络时,我发现了“判别式”和特别是像这样的比较函数:particular

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

很遗憾,在我的情况下,此功能无法正常工作:

#[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

理想情况下,我希望我的代码像这样使用 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!!!") }

1
可能是如何为枚举实现PartialEq?的重复问题。 - jonny
1个回答

7

这个答案中找到了一个合适的解决方案。使用#[derive(PartialEq)]为枚举定义部分相等,使用==来比较它们: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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接