【问题标题】:How to filter collection by a tuple Enum如何通过元组枚举过滤集合
【发布时间】: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 次不同的比较,我觉得应该有更好的方法,我还没有找到。

【问题讨论】:

    标签: rust enums


    【解决方案1】:

    我相信,您正在寻找 matches! 宏:

    .filter(|e| matches!(e.1, Item::Weapons(_))
    

    游乐场:https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=efe0c91651ffbf952d07d49f1d6b19ce

    【讨论】:

    • 太完美了!谢谢:)
    【解决方案2】:

    以下是完成这项工作所必需的:

    .filter(|e| match *e.1 { Item::Weapons(_) => true, _ => false })
    // or .filter(|e| if let Item::Weapons(_) = *e.1 { true } else { false })
    

    您无法创建具有关联数据但没有关联数据的枚举变体,这是您尝试做的。您必须将*e.1 中的值与某种模式进行模式匹配,在这种情况下,Item::Weapons(_)_ 占位符作为枚举中的有效负载值,因为您不关心枚举中的确切内容。

    游乐场:https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=42d462c4c83900202b0c00c7ba612f77

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      • 2020-05-04
      • 2012-08-19
      • 1970-01-01
      相关资源
      最近更新 更多