enums - 比较 Rust 中的嵌套枚举变体
问题描述
学习 Rust 我碰巧需要比较嵌套枚举中的变体。考虑以下枚举,我如何比较实例化的实际变体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)
}
不幸的是,这个功能在我的情况下不起作用:
#[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!!!") }
解决方案
在这个答案中找到了合适的解决方案。用于#[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);
推荐阅读
- python - Ctypes Cuda - 指针乘法不会导致产品
- python - 姜戈 | 使用猴子补丁在 3rd 方包中添加/更改代码
- c++ - 在 c++ 中是一个 += 对 std::string 的安全
- python - 安装后,Functions-framework 不会在 Windows 命令行中运行
- python - 如何在格式化为字典的 XML 中查找某些键的值?Python
- linux - 通过 Plesk Schedule Task 重启 mysql 服务
- python - 如何在 discord.py 中创建多个循环后台任务(不重写)
- flutter - 在 initState 中更改 bool
- python - 将玩家移动到特定房间
- c# - 具有“Dock”调整大小功能的重叠面板