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

dougli1sqrd picture dougli1sqrd · Jan 27, 2014 · Viewed 27k times · Source

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 turn with the enhanced for loop like:

for(Direction dir : Direction.values())  {
    //do something with dir
}

I would like to do a similar thing with Rust enums.

Answer

Jordan Mack picture Jordan Mack · Mar 8, 2019

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