Skip to content

Derive EnumIter

Peter Glotfelty edited this page Aug 18, 2019 · 1 revision

Iterate over the variants of an Enum. Any additional data on your variants will be set to Default::default(). The macro implements strum::IntoEnumIter on your enum and creates a new type called YourEnumIter that is the iterator object. You cannot derive EnumIter on any type with a lifetime bound (<'a>) because the iterator would surely create unbounded lifetimes.

// You need to bring the type into scope to use it!!!
use strum::IntoEnumIterator;

#[derive(EnumIter,Debug)]
enum Color {
    Red,
    Green { range:usize },
    Blue(usize),
    Yellow,
}

// It's simple to iterate over the variants of an enum.
fn debug_colors() {
    for color in Color::iter() {
        println!("My favorite color is {:?}", color);
    }
}

fn main() {
    debug_colors();
}
Clone this wiki locally