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