Skip to main content
freelanceshack.com

Back to all posts

How to Use Pattern Matching In Rust?

Published on
5 min read
How to Use Pattern Matching In Rust? image

Best Rust Programming Books to Buy in October 2025

1 The Rust Programming Language, 2nd Edition

The Rust Programming Language, 2nd Edition

BUY & SAVE
$30.13 $49.99
Save 40%
The Rust Programming Language, 2nd Edition
2 Programming Rust: Fast, Safe Systems Development

Programming Rust: Fast, Safe Systems Development

BUY & SAVE
$43.99 $79.99
Save 45%
Programming Rust: Fast, Safe Systems Development
3 Rust for Rustaceans: Idiomatic Programming for Experienced Developers

Rust for Rustaceans: Idiomatic Programming for Experienced Developers

BUY & SAVE
$29.99 $49.99
Save 40%
Rust for Rustaceans: Idiomatic Programming for Experienced Developers
4 Rust in Action

Rust in Action

BUY & SAVE
$51.42 $59.99
Save 14%
Rust in Action
5 Rust Programming: A Practical Guide to Fast, Efficient, and Safe Code with Ownership, Concurrency, and Web Programming (Rheinwerk Computing)

Rust Programming: A Practical Guide to Fast, Efficient, and Safe Code with Ownership, Concurrency, and Web Programming (Rheinwerk Computing)

BUY & SAVE
$47.04 $59.95
Save 22%
Rust Programming: A Practical Guide to Fast, Efficient, and Safe Code with Ownership, Concurrency, and Web Programming (Rheinwerk Computing)
6 Zero To Production In Rust: An introduction to backend development

Zero To Production In Rust: An introduction to backend development

BUY & SAVE
$49.99
Zero To Production In Rust: An introduction to backend development
7 The Rust Programming Language

The Rust Programming Language

BUY & SAVE
$16.92 $39.95
Save 58%
The Rust Programming Language
8 Rust Atomics and Locks: Low-Level Concurrency in Practice

Rust Atomics and Locks: Low-Level Concurrency in Practice

BUY & SAVE
$33.13 $55.99
Save 41%
Rust Atomics and Locks: Low-Level Concurrency in Practice
9 Asynchronous Programming in Rust: Learn asynchronous programming by building working examples of futures, green threads, and runtimes

Asynchronous Programming in Rust: Learn asynchronous programming by building working examples of futures, green threads, and runtimes

BUY & SAVE
$28.90 $49.99
Save 42%
Asynchronous Programming in Rust: Learn asynchronous programming by building working examples of futures, green threads, and runtimes
10 Refactoring to Rust

Refactoring to Rust

BUY & SAVE
$49.99
Refactoring to Rust
+
ONE MORE?

Pattern matching in Rust allows the developer to match the structure of data against predefined patterns and execute corresponding code blocks. It is a powerful feature that simplifies data extraction and helps in handling different cases efficiently.

To use pattern matching, you can utilize the match statement. It enables you to compare a value against a series of patterns and execute code based on the match.

Here's a general structure of a match statement in Rust:

match value { pattern1 => { // code to execute if pattern1 matches }, pattern2 => { // code to execute if pattern2 matches }, _ => { // code to execute if none of the patterns match } }

In the above code, value is the value being matched against the patterns. Each pattern can be a constant, a variable, or a combination of different patterns.

Here are a few examples of how pattern matching can be used in Rust:

  1. Matching an exact value:

let x = 5;

match x { 5 => println!("The value is 5"), _ => println!("Not a match"), }

  1. Matching a range of values:

let age = 20;

match age { 0..=17 => println!("You are a minor"), 18..=64 => println!("You are an adult"), _ => println!("You are a senior citizen"), }

  1. Extracting values from an enum:

enum Shape { Circle(f64), Square(f64), Rectangle(f64, f64), }

let shape = Shape::Rectangle(5.0, 6.0);

match shape { Shape::Circle(radius) => println!("Circle with radius {}", radius), Shape::Square(side_length) => println!("Square with side length {}", side_length), Shape::Rectangle(length, width) => println!("Rectangle with length {} and width {}", length, width), }

These are just basic examples, but pattern matching can be used in many more complex scenarios in Rust. It provides a concise and expressive way to handle different cases and can greatly enhance your code readability and maintainability.

How can I pattern match on function return values in Rust?

In Rust, pattern matching can be used to extract and handle different cases of function return values. You can use the match expression to pattern match on the returned value and handle each possibility separately.

Here's an example that demonstrates how to pattern match on function return values in Rust:

fn divide_divisible(a: i32, b: i32) -> Result<i32, &'static str> { if b == 0 { return Err("Cannot divide by zero"); }

Ok(a / b)

}

fn main() { let result = divide_divisible(10, 2);

match result {
    Ok(value) => println!("Result: {}", value),
    Err(error) => println!("Error: {}", error),
}

}

In this example, the divide_divisible function divides two integers and returns a Result type that represents either a successful division (Ok) or an error message (Err). The match expression in the main function allows pattern matching on result.

If the result is Ok, the inner value can be extracted and printed accordingly. If the result is Err, the error message can be extracted and printed.

This way, you can handle different cases of return values using pattern matching in Rust.

What is the purpose of the @ operator in pattern matching?

The purpose of the "@" operator in pattern matching is to bind a pattern to a value and at the same time destructure the value to access its components. It allows you to use a pattern with a variable name to bind a value to that variable, as well as break down the structure of the value.

For example, in functional programming languages like F# or Haskell, you can use the "@" operator to match a list or a tuple and bind its components to variables. Here's a simple example in F#:

let printFirstAndLast list = match list with | [] -> () | [x] -> printfn "Only one element: %A" x | first :: rest :: @last -> printfn "First: %A, Last: %A" first last

In this example, the pattern [first :: rest :: @last] matches a list with at least two elements, and binds the first element to first, the rest of the list to rest, and the last element to last. This allows you to access and work with these components within the body of the match case.

The "@" operator provides a convenient way to simultaneously bind a value to a variable and destructure it for further processing, thus enhancing the expressive power of pattern matching.

How can I match specific values in Rust?

To match specific values in Rust, you can use the match expression. Here is an example:

fn main() { let value = 5;

match value {
    1 => println!("Value is 1"),
    2 => println!("Value is 2"),
    3 | 4 => println!("Value is 3 or 4"),
    5..=10 => println!("Value is between 5 and 10"),
    \_ => println!("Value is something else"),
}

}

In this example, the match expression compares the value against several patterns. If the value matches a pattern, the corresponding branch is executed. Here is what each pattern does:

  • 1 matches if the value is exactly 1.
  • 2 matches if the value is exactly 2.
  • 3 | 4 matches if the value is either 3 or 4.
  • 5..=10 matches if the value is between 5 and 10 (inclusive).
  • _ is a wildcard pattern that matches any value. It acts as a catch-all for values that don't match any other pattern.

You can replace the println! statements with any other code to perform the desired actions based on the matched values.