【发布时间】:2021-10-25 20:37:08
【问题描述】:
我有一个像这样运行的程序的一部分,我需要一种使用枚举过滤集合的方法,但我不确定允许“子枚举”的所有可能性的最佳方法。
在示例中,我想打印所有武器,无论它是什么类型。
use std::collections::BTreeMap;
#[derive(PartialEq, Eq)]
enum Item {
Armor,
Consumable,
Weapons(WeaponTypes),
}
#[derive(PartialEq, Eq)]
enum WeaponTypes {
Axe,
Bow,
Sword,
}
fn main() {
let mut stuff = BTreeMap::<&str, Item>::new();
stuff.insert("helmet of awesomeness", Item::Armor);
stuff.insert("boots of the belligerent", Item::Armor);
stuff.insert("potion of eternal life", Item::Consumable);
stuff.insert("axe of the almighty", Item::Weapons(WeaponTypes::Axe));
stuff.insert("shortbow", Item::Weapons(WeaponTypes::Bow));
stuff.insert("sword of storm giants", Item::Weapons(WeaponTypes::Sword));
stuff
.iter()
// this filter works exactly as intended
.filter(|e| *e.1 == Item::Armor)
// using this filter instead doesn't work because it expects a WeaponType inside
//.filter(|e| e.1 == Item::Weapons)
.map(|e| e.0.to_string())
.for_each(|e| println!("'{}'", e));
}
我尝试使用 Item::WeaponType(_),因为这有点像 _ 匹配案例,但这也行不通。
作为最后的手段,我可以将等式表达式链接在一起 (e.1 == Item::Weapons(WeaponType::Axe) || e.1 == Item::Weapons(WeaponType::Sword) ...),但这需要进行 8 次不同的比较,我觉得应该有更好的方法,我还没有找到。
【问题讨论】: