Rust pattern matching
Created By: chatGPT
Pattern matching in Rust is a powerful feature that allows you to compare a value against a series of patterns. It's often used with enums, structs, and even primitive types. The most common way to employ pattern matching in Rust is through the
match
statement, but you can also use if let
and while let
for more succinct scenarios.let number = 7;
match number {
1 => println!("One"),
2 => println!("Two"),
3 => println!("Three"),
4..=6 => println!("Between Four and Six"),
_ => println!("Something else"),
}
In the example above, the
match
statement checks the value of number
. When it matches one of the patterns, it executes the corresponding block of code. The _
pattern acts as a catch-all for any values that don't match the previous patterns.let value = Some(10);
if let Some(x) = value {
println!("Value is: {}", x);
} else {
println!("No value found");
}
Using
if let
allows you to match and unpack a value in a more concise way when you're only interested in one specific pattern. In the example above, if value
is Some(10)
, it will print the value inside.struct Point {
x: i32,
y: i32,
}
let point = Point { x: 10, y: 20 };
match point {
Point { x, y } if x == y => println!("Point is on the diagonal"),
Point { x, y } => println!("Point is at ({}, {})", x, y),
}
Rust also allows you to match against structural patterns, as shown with the
Point
struct example above. The if
condition inside the match
arm checks if the x and y coordinates are equal, allowing for additional logic within the pattern match.let values = [1, 2, 3, 4, 5];
while let Some(value) = values.iter().next() {
println!("Current value: {}", value);
break;
}
Finally, the
You can also use pattern matching with enums, like the while let
construct can be used for iterators or when you're working with options. In the example, it retrieves the next value from an array until there are no more values left. Make sure to use break
to prevent an infinite loop in this case.enum TrafficLight {
Red,
Yellow,
Green,
}
let light = TrafficLight::Red;
match light {
TrafficLight::Red => println!("Stop"),
TrafficLight::Yellow => println!("Caution"),
TrafficLight::Green => println!("Go"),
}
TrafficLight
example above. Each variant of the enum can be matched with its respective actions. This makes your code readable and organized, especially when dealing with multiple states or conditions.