Pattern Syntax in Rust 🎯

beginner
19 min

Pattern Syntax in Rust 🎯

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:

  • Understand the basics of pattern matching in Rust
  • Learn how to use different types of patterns for various data structures
  • Discover advanced techniques for more complex pattern matching scenarios

What is Pattern Syntax? 📝

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.

Basic Pattern Matching 💡

Let's start with a simple example of pattern matching with enum types:

rust
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.

Advanced Pattern Matching 💡

Rust allows us to create more complex patterns for matching against data structures. Let's dive into some examples:

Matching Tuples

rust
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).

Matching Multiple Values

rust
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.

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `match` keyword do in Rust?

Quick Quiz
Question 1 of 1

What is the purpose of pattern matching with tuples in Rust?

Quick Quiz
Question 1 of 1

How does the `match` keyword know which pattern to use for a given data structure?