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

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

Leave a Comment