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

前端 未结 5 2055
春和景丽
春和景丽 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:16

    You can use the strum crate to easily iterate through the values of an enum.

    use strum::IntoEnumIterator; // 0.17.1
    use strum_macros::EnumIter; // 0.17.1
    
    #[derive(Debug, EnumIter)]
    enum Direction {
        NORTH,
        SOUTH,
        EAST,
        WEST,
    }
    
    fn main() {
        for direction in Direction::iter() {
            println!("{:?}", direction);
        }
    }
    

    Output:

    NORTH
    SOUTH
    EAST
    WEST
    

提交回复
热议问题