Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Enums 比较Rust中的嵌套枚举变量_Enums_Rust_Comparison - Fatal编程技术网

Enums 比较Rust中的嵌套枚举变量

Enums 比较Rust中的嵌套枚举变量,enums,rust,comparison,Enums,Rust,Comparison,我碰巧需要比较嵌套枚举中的变量。考虑到以下枚举,如何比较InstantiatedBuffTurget的实际变体 enum Attribute { Strength, Agility, Intellect, } enum Parameter { Health, Mana, } enum BuffTarget { Attribute(Attribute), Parameter(Parameter), } 通过搜索网页,我找到了“判别式”和类似的比较功

我碰巧需要比较嵌套枚举中的变量。考虑到以下枚举,如何比较Instantiated
BuffTurget
的实际变体

enum Attribute {
  Strength,
  Agility,
  Intellect,
}

enum Parameter {
    Health,
    Mana,
}

enum BuffTarget {
    Attribute(Attribute),
    Parameter(Parameter),
}
通过搜索网页,我找到了“判别式”和类似的比较功能:

fn variant_eq<T>(a: &T, b: &T) -> bool {
    std::mem::discriminant(a) == std::mem::discriminant(b)
}
理想情况下,我希望我的代码是这样的,使用
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!!!") }

找到合适的解决方案。对枚举使用
#[派生(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);
可能重复的
#[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);