rust match enum
Rust: Matching Enums
In Rust, you can use the match
expression to match and handle different variants of an enum. The match
expression allows you to compare the value of an enum and execute different code based on the matched variant.
Here's the general syntax of the match
expression in Rust:
match value {
Variant1 => {
// code to execute when value matches Variant1
},
Variant2 => {
// code to execute when value matches Variant2
},
// more patterns...
}
Each variant of the enum is listed as a pattern, followed by the code to execute when the value matches that pattern. You can have multiple patterns separated by commas.
Here's an example that demonstrates the usage of match
with an enum:
enum Fruit {
Apple,
Banana,
Orange,
}
fn main() {
let fruit = Fruit::Apple;
match fruit {
Fruit::Apple => {
println!("It's an apple!");
},
Fruit::Banana => {
println!("It's a banana!");
},
Fruit::Orange => {
println!("It's an orange!");
},
}
}
In this example, the match
expression is used to match the fruit
variable against the different variants of the Fruit
enum. The code inside each arm of the match
expression is executed based on the matched variant.
Please let me know if you need further assistance!