rustHow to loop through enum in Rust
Looping through an enum in Rust is done using a match expression. The match expression allows you to match each variant of the enum and execute code for each variant. The following ## Code example shows how to loop through an enum and print out each variant:
enum MyEnum {
Variant1,
Variant2,
Variant3,
}
fn main() {
let my_enum = MyEnum::Variant1;
match my_enum {
MyEnum::Variant1 => println!("Variant1"),
MyEnum::Variant2 => println!("Variant2"),
MyEnum::Variant3 => println!("Variant3"),
}
}
Output example:
Variant1
Explanation
The ## Code example uses a match expression to loop through the enum. The match expression takes the enum as an argument and then matches each variant of the enum. For each variant, a code block is executed. In this example, the code block prints out the variant name.
Helpful links
Related
More of Rust
- Hashshet example in Rust
- How to convert Rust bytes to hex?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to get the last element of a Rust slice?
- How to use non-capturing groups in Rust regex?
- How to use groups in a Rust regex?
- How to match the end of a line in a Rust regex?
- How to escape dots with regex in Rust?
- How to use regex to match a group in Rust?
See more codes...