Directly iterating over all values of an enum in Rust is not natively supported because Rust enums can contain data of different types and varying numbers of fields, which makes automatic iteration complex. However, you can achieve this by implementing an iterator or using a third-party library.
A common approach is to use the strum library, which provides functionality for iterating over enums. First, add the strum and strum_macros dependencies to your Cargo.toml:
toml[dependencies] strum = "0.20" strum_macros = "0.20"
Then, use the EnumIter macro from strum_macros to automatically generate iteration-related code for your enum type:
rustuse strum_macros::EnumIter; use strum::IntoEnumIterator; #[derive(Debug, EnumIter)] enum Color { Red, Blue, Green, } fn main() { for color in Color::iter() { println!("{:?}", color); } }
This code will print all enum values: Red, Blue, and Green. Using the strum library is a convenient way to iterate over enum values.