我有一个像这样运行的程序的一部分,我需要一种使用枚举来过滤集合的方法,但我不确定允许“子枚举”的所有可能性的最佳方法。
在示例中,我想打印所有武器,无论它是什么类型。
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));
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用Item::WeaponType(_),因为这看起来有点像火柴盒_,但这也行不通。
我可以将等式表达式链接在一起作为最后的手段(e.1 == Item::Weapons(WeaponType::Axe) || e.1 == Item::Weapons(WeaponType::Sword) ...),但这需要 8 次不同的比较,而且我觉得应该有更好的方法,但我还没有找到。
我相信,您正在寻找匹配的人!宏:
.filter(|e| matches!(e.1, Item::Weapons(_))
Run Code Online (Sandbox Code Playgroud)