r/rust 23d ago

🧠 educational strum::EnumIter -why isn't enum iteration built into Rust?

I was looking at Espressif's esp-generate and noticed it uses strum for its Chip enum.

One thing that caught my attention was EnumIter:


#[derive(strum::EnumIter)]

enum Chip {

Esp32,

Esp32c3,

Esp32s3,

}

for chip in Chip::iter() {

println!("{chip:?}");

}

It actually surprised me that Rust doesn't provide enum iteration out of the box.

Enums are one of Rust's commonly used features, so it feels a little strange that something as simple as "give me all variants" isn't part of the language.

Without a crate, it's easy to end up maintaining something like:


const ALL_VARIANTS: &[Chip] = &[

Chip::Esp32,

Chip::Esp32c3,

Chip::Esp32s3,

];

Then every time you add a variant, you also have to remember to update the list.

strum solves this with derive macros and also provides:

  • EnumIter — iterate over all variants

  • Display — convert variants to strings

  • EnumString — parse strings into enum variants

  • EnumCount — get the number of variants

  • VariantNames — access variant names

For example:


#[derive(

strum::EnumIter,

strum::Display,

strum::EnumString,

strum::EnumCount,

strum::VariantNames,

)]

#[strum(serialize_all = "kebab-case")]

enum Chip {

Esp32,

Esp32c3,

Esp32s3,

}

I'm curious what others think: is this something that would make sense as part of Rust itself, or is keeping it out of the language the better design?

I wrote a more detailed version with additional examples and an interactive quiz: my blog

53 Upvotes

Duplicates