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
- How to create enum from string in Rust
- How to use enum as hashmap key in Rust
- How to create enum from number in Rust
- How to use fmt for enum in Rust
- How to declare enum in Rust
- How to print enum in Rust
- How to compare enum in Rust
- How to create enum from int in Rust
- Get enum value by index in Rust
- How to cast enum in Rust
More of Rust
- How to replace strings using Rust regex?
- How to get a capture group using Rust regex?
- How to use regex to match a group in Rust?
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use regex to match a double quote in Rust?
- How to match the end of a line in a Rust regex?
- How to get an entry from a HashSet in Rust?
- Word boundary example in regex in Rust
See more codes...