How to Iterate through the Values of an Enum in Rust
Created
Modified
Using a static array
If the enum is C-like, 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 direction in Direction::iterator() {
println!("{:?}", direction);
}
}
North South East West
Using strum Crate
Install
Add the following line to your Cargo.toml file:
[dependencies]
strum = "0.24"
strum_macros = "0.24"
# You can also use the "derive" feature, and import the macros directly from "strum"
# strum = { version = "0.24", features = ["derive"] }
Strum Usage
Strum is a set of macros and traits for working with enums and strings easier in Rust.
// You need to bring the trait into scope to use it!
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
#[derive(Debug, EnumIter)]
pub enum Direction {
North,
South,
East,
West,
}
fn main() {
for direction in Direction::iter() {
println!("{:?}", direction);
}
}
North South East West