Rust match arm
Created By: chatGPT
Rust provides a powerful control flow operator called
match
that is used to compare a value against a series of patterns. Each pattern can lead to different outcomes based on the value of the input. This feature offers great versatility in matching capabilities. Here's the basic syntax for a match statement:let number = 3;
match number {
1 => println!("One"),
2 => println!("Two"),
3 => println!("Three"),
_ => println!("Not One, Two, or Three"),
}
In the example above, we defined a variable
number
and then used match
to check its value. The underscore (_
) is a catch-all pattern that will match any value not covered by the previous patterns.let character = 'c';
match character {
'a' | 'e' | 'i' | 'o' | 'u' => println!("Vowel"),
_ => println!("Consonant"),
}
In this example, we match against a character value to determine if it is a vowel or a consonant. The pipe
|
operator allows us to match multiple patterns simultaneously.enum Direction {
Up,
Down,
Left,
Right,
}
let move = Direction::Left;
match move {
Direction::Up => println!("Moving Up"),
Direction::Down => println!("Moving Down"),
Direction::Left => println!("Moving Left"),
Direction::Right => println!("Moving Right"),
}
You can also use
match
with enums. In the example above, we defined a Direction
enum and matched it to output a corresponding message based on the direction.struct Point {
x: i32,
y: i32,
}
let point = Point { x: 0, y: 0 };
match point {
Point { x: 0, y: 0 } => println!("At Origin"),
Point { x, y } if x == y => println!("On the line y = x"),
_ => println!("Not on the line"),
}
Patterns can also include destructuring of structs. In the last example, we took a
Point
struct and matched its x
and y
values, demonstrating how we can add a guard clause with an if
condition.let option_value = Some(7);
match option_value {
Some(x) if x > 5 => println!("Value is greater than 5: {}", x),
Some(x) => println!("Value is: {}", x),
None => println!("No value"),
}
The
match
statement can handle Options and includes guard clauses as well. In the last snippet, we check if the value inside Some
is greater than 5 and then print the appropriate message.// Using match to handle error types
let result: Result<i32, &str> = Err("An error occurred");
match result {
Ok(value) => println!("Success: {}", value),
Err(err) => println!("Error: {}", err),
}
Finally,
match
can also be used to handle the Result type to differentiate between success and error cases. This highlights the power and flexibility of the match
expression in Rust, allowing you to write more robust programs.let value = match some_function() {
Ok(v) => v,
Err(e) => {
eprintln!("Error: {}", e);
return;
},
};