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
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to clear a Rust HashMap?
- Yield example in Rust
- Example of yield_now in Rust?
- How to convert a Rust slice to a fixed array?
- How to use regex to match a group in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to yield a thread in Rust?
- How to replace strings using Rust regex?
See more codes...