< 返回版块

Spxg 发表于 2021-09-11 11:42

项目地址:https://github.com/Spxg/filter

使用 filter-macros,然后对一个枚举体实现 Filter Trait,填上判断规则(rules),就可以用了。

#[add_fields]
#[derive(BitAnd, BitOr, OpUnitTrait)]
enum NumType {
    Odd,
    Even,
    DivByThree,
    DivByFour,
    DivByFive,
    IsMagicNum(i32),
}

impl Filter for NumType {
    type Item = i32;

    fn rules(&self, item: &Self::Item) -> bool {
        match self {
            NumType::Odd => item % 2 != 0,
            NumType::Even => item % 2 == 0,
            NumType::DivByThree => item % 3 == 0,
            NumType::DivByFour => item % 4 == 0,
            NumType::DivByFive => item % 5 == 0,
            NumType::IsMagicNum(num) => item == num,
            _ => false,
        }
    }
}

fn main() {
    let nums = vec![1, 2, 3, 4, 5, 6, 9, 12, 15, 16, 20, 22, 24, 1024];
    let test = NumType::Odd
        | NumType::Even & NumType::DivByThree & NumType::DivByFour
        | NumType::DivByFive;
    let result = nums
        .clone()
        .into_iter()
        .filter(test.ref_one_filter())
        .collect::<Vec<_>>();
    assert_eq!(vec![1, 3, 5, 9, 12, 15, 20, 24], result);

    let test = NumType::IsMagicNum(1024);
    assert!(test.self_filter()(1024));
}

Ext Link: https://github.com/Spxg/filter

评论区

写评论

还没有评论

1 共 0 条评论, 1 页