Welcome to the Pattern Syntax lesson, where we'll explore the intricacies of matching data using patterns in Rust!
By the end of this tutorial, you'll be able to:
Pattern syntax in Rust is used to match data structures like tuples, arrays, and enum types against patterns. This helps us to extract specific values from the data structures and perform actions based on the matched pattern.
Let's start with a simple example of pattern matching with enum types:
enum Shape {
Circle(f64),
Rectangle(f64, f64),
}
fn area(shape: Shape) {
match shape {
Shape::Circle(radius) => 3.14 * radius * radius,
Shape::Rectangle(length, width) => length * width,
}
}In the above example, we have an enum named Shape with two variants: Circle and Rectangle. We define a function area that takes a Shape as an argument and calculates the area based on the matched pattern.
Rust allows us to create more complex patterns for matching against data structures. Let's dive into some examples:
fn print_coordinates((x, y): (i32, i32)) {
println!("x: {}, y: {}", x, y);
}In this example, we define a function print_coordinates that takes a tuple as an argument and matches it against the pattern (i32, i32).
enum Result {
Ok(i32),
Err(String),
}
fn process(result: Result) {
match result {
Result::Ok(value) => println!("Result is Ok: {}", value),
Result::Err(error_msg) => println!("Error occurred: {}", error_msg),
}
}In the above example, we define an enum named Result with two variants: Ok and Err. We then define a function process that takes a Result as an argument and matches it against the pattern Result::Ok or Result::Err.
What does the `match` keyword do in Rust?
What is the purpose of pattern matching with tuples in Rust?
How does the `match` keyword know which pattern to use for a given data structure?