Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Iterate over the variants of an enum

Sometimes we need to go over all the variants of an enum and do something for each one of them.

[package]
name = "list-variants"
version = "0.1.0"
edition = "2021"

[dependencies]
strum = "0.26.3"
strum_macros = "0.26.4"
use strum::IntoEnumIterator;
use strum_macros::EnumIter;

#[derive(EnumIter, Debug, PartialEq)]
enum Animal {
    Cat,
    Dog,
    Snake,
    Camel,
    Crab,
}

fn main() {
    for animal in Animal::iter() {
        println!("{animal:?}");
    }
}
Cat
Dog
Snake
Camel
Crab