rust iterate over enum

To iterate over an enum in Rust, you can use a match expression and a loop. Here is an example of how you could do it:

#[derive(Debug)]
enum Color {
    Red,
    Green,
    Blue,
}

fn main() {
    let colors = [Color::Red, Color::Green, Color::Blue];

    for color in colors.iter() {
        match color {
            Color::Red => println!("The color is Red"),
            Color::Green => println!("The color is Green"),
            Color::Blue => println!("The color is Blue"),
        }
    }
}

This will print:

The color is Red
The color is Green
The color is Blue

You can also use a for loop to iterate over the variant values of the enum directly, like this:

rust iterate over enum

#[derive(Debug)]
enum Color {
    Red,
    Green,
    Blue,
}

fn main() {
    for color in Color::iter() {
        match color {
            Color::Red => println!("The color is Red"),
            Color::Green => println!("The color is Green"),
            Color::Blue => println!("The color is Blue"),
        }
    }
}

This will also print:

The color is Red
The color is Green
The color is Blue

If you want to use the for loop to iterate over the variant values of the enum and also get the index of each value in the loop, you can use the enumerate() method on the iter() method, like this:

#[derive(Debug)]
enum Color {
    Red,
    Green,
    Blue,
}

fn main() {
    for (i, color) in Color::iter().enumerate() {
        println!("The index is {} and the color is {:?}", i, color);
    }
}

This will print:

The index is 0 and the color is Red
The index is 1 and the color is Green
The index is 2 and the color is Blue

 

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *