我有一個程序的一部分具有這樣的功能,我需要一種使用枚舉過濾集合的方法,但我不確定允許“子枚舉”的所有可能性的最佳方法。
在這個例子中,我想打印所有武器,不管它是什麼類型。
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 次不同的比較,而且我覺得應該有更好的方法,但我還沒有找到。
我相信,你正在尋找一個火柴!宏:
.filter(|e| matches!(e.1, Item::Weapons(_))
操場:https : //play.rust-lang.org/? version = stable & mode = debug & edition = 2021 & gist =efe0c91651ffbf952d07d49f1d6b19ce
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句