In Rust, is there a way to iterate through the values of an enum?

前端 未结 5 2053
春和景丽
春和景丽 2020-12-08 03:52

I come from a Java background and I might have something like enum Direction { NORTH, SOUTH, EAST, WEST} and I could do something with each of the values in tur

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 04:22

    If the enum is C-like (as in your example), then you can create a static array of each of the variants and return an iterator of references to them:

    use self::Direction::*;
    use std::slice::Iter;
    
    #[derive(Debug)]
    pub enum Direction {
        North,
        South,
        East,
        West,
    }
    
    impl Direction {
        pub fn iterator() -> Iter<'static, Direction> {
            static DIRECTIONS: [Direction; 4] = [North, South, East, West];
            DIRECTIONS.iter()
        }
    }
    
    fn main() {
        for dir in Direction::iterator() {
            println!("{:?}", dir);
        }
    }
    

    If you make the enum implement Copy, you can use Iterator::copied and return impl Trait to have an iterator of values:

    impl Direction {
        pub fn iterator() -> impl Iterator {
            [North, South, East, West].iter().copied()
        }
    }
    

    See also:

    • What is the correct way to return an Iterator (or any other trait)?
    • Why can I return a reference to a local literal but not a variable?

提交回复
热议问题