How to compare enum without pattern matching

前端 未结 3 796
旧时难觅i
旧时难觅i 2020-12-15 14:56

I want to apply filter on an iterator and I came up with this one and it works, but it\'s super verbose:

.filter(|ref my_struct| match my_struct         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 15:53

    I'd use pattern matching, but I'd move it to a method on the enum so that the filter closure is tidier:

    #[derive(Debug)]
    enum Thing {
        One(i32),
        Two(String),
        Unknown,
    }
    
    impl Thing {
        fn is_unknown(&self) -> bool {
            match *self {
                Thing::Unknown => true,
                _ => false,
            }
        }
    }
    
    fn main() {
        let things = vec![Thing::One(42), Thing::Two("hello".into()), Thing::Unknown];
        for t in things.iter().filter(|s| !s.is_unknown()) {
            println!("{:?}", t);
        }
    }
    

    See also:

    • Compare enums only by variant, not value

提交回复
热议问题