Iterating Through Enum Values in Rust

1. Overview

Iterating through an Enum value may be tricky in Rust. However, a third-party crate called strum makes the process easier.

In this tutorial, we’ll explore how to use strum to iterate over an Enum in Rust.

2. Iterate Through an Enum Using strum

To begin with, let’s create a new project named iterate-enum:

$ cargo init iterate-enum

Next, let’s add a strum crate to the Cargo.toml file:

[dependencies]
strum = { version = "0.25.0", features=["derive"]}
We now have strum dependencies in our project.

Let’s write a simple code that iterates over the value of an enum. First, let’s create an Enum of countries:

#[derive(Debug, EnumIter, PartialEq)]
pub enum Countries {
    USA,
    UK,
    Canada,
    Russia,
    India,
}

Here, we inject the EnumIter trait to help iterate through the Enum value. EnumIter is a third-party crate from strum. Next, let’s iterate through the values:

for country in Countries::iter() {
    print!("{:?}\n", country);
}
In the code above, we iterate through the Enum and output the result to the console.

3. Conclusion

In this tutorial, we learn how to use strum crate to iterate through an enum in Rust

The complete example code is available on Rust playground.