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.
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