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 int in Rust
- How to print enum in Rust
- How to uppercase enum in Rust
- How to compare enum in Rust
- How to get all enum values in Rust
- Get enum value by index in Rust
- How to use enum as hashmap key in Rust
- How to get enum value in Rust
- Enum as u32 in Rust
- Using enum in json in Rust
More of Rust
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to replace all matches using Rust regex?
- How to replace strings using Rust regex?
- How to split a string with Rust regex?
- How to parse JSON string in Rust?
- How to use regex captures in Rust?
- How to use negation in Rust regex?
See more codes...