The Rust Programming Language — Pattern Matching — Pattern matching using Enums
4 min readOct 16, 2023
Enums can be used to match the pattern against literals. Literals are nothing but the variant
inside the enum
.
Rust provides us with a keyword called match
which is basically like a switch case statement in other languages. Using match keyword, you can create blocks of code which should execute when the variable(case) matches the literal value.
Take for e.g. below code snippet:
enum Color {
Red,
Yellow,
Green
}
fn main() {
let current_color: Color = Color::Green;
match current_color {
Color::Red => {
println!("The color is Red!");
}
Color::Yellow => {
println!("The color is Yellow!");
}
Color::Green => {
println!("The color is Green!");
}
}
}
Observations:
- We use the
match
keyword on the variable/case on which we want to execute the pattern matching. - We
match
on a variable namedcurrent_color
and we create a pattern matching for eachvariant
ofenum
Color
identifier
using namespace
Since Rust is a strict programming language, the only issue with doing pattern matching on an enum
is that you need to handle each and every variant
. So for the…