Rust match Statement
Tags: rust, webdev, programming
Published: 2023-12-31 06:23:19

The `match` statement in Rust is a powerful control flow construct used for pattern matching. It allows you to match a value against a series of patterns and execute different code blocks based on the matched pattern.

Example code:
```rust
fn main() {
    let number = 7;

    match number {
        1 => println!("One"),
        2 => println!("Two"),
        3 => println!("Three"),
        _ => println!("Other"),
    }
}
```

**Matching Against Multiple Patterns**
In Rust, you can match against multiple patterns in a single `match` statement. The first matching pattern will be executed.

Example code:
```rust
fn main() {
    let number = 3;

    match number {
        1 | 2 => println!("One or Two"),
        3 | 4 => println!("Three or Four"),
        _ => println!("Other"),
    }
}
```

**Matching with Binding**
The `match` statement in Rust allows you to bind the matched value to a variable, which can be used in the corresponding code block.

Example code:
```rust
fn main() {
    let number = Some(7);

    match number {
        Some(n) => println!("Found a number: {}", n),
        None => println!("No number found"),
    }
}
```

**Ignoring Values**
If you don't need to use the matched value, you can use the underscore (`_`) pattern to ignore it.

Example code:
```rust
fn main() {
    let number = Some(7);

    match number {
        Some(_) => println!("Found a number"),
        None => println!("No number found"),
    }
}
```

**Matching with Guards**
Rust's `match` statement supports guards, which are additional conditions that can be added to the patterns.

Example code:
```rust
fn main() {
    let age = 18;

    match age {
        0..=17 => println!("Underage"),
        18..=65 => println!("Adult"),
        _ => println!("Senior Citizen"),
    }
}
```

I hope these help you understand the Rust `match` statement better!


Here are a few more examples of using the `match` statement in Rust:

**Example 1: Matching Enum Variants**
```rust
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn process_message(msg: Message) {
    match msg {
        Message::Quit => println!("Quit message received"),
        Message::Move { x, y } => println!("Move to {}, {}", x, y),
        Message::Write(text) => println!("Write message: {}", text),
        Message::ChangeColor(r, g, b) => println!("Change color to ({}, {}, {})", r, g, b),
    }
}

fn main() {
    let msg1 = Message::Move { x: 10, y: 20 };
    let msg2 = Message::Write(String::from("Hello, Rust!"));

    process_message(msg1);
    process_message(msg2);
}
```

**Example 2: Matching Option Values**
```rust
fn get_favorite_fruit(name: &str) -> Option<&str> {
    match name {
        "Alice" => Some("Apple"),
        "Bob" => Some("Banana"),
        _ => None,
    }
}

fn main() {
    let name1 = "Alice";
    let name2 = "Charlie";

    match get_favorite_fruit(name1) {
        Some(fruit) => println!("{}'s favorite fruit is {}", name1, fruit),
        None => println!("{}'s favorite fruit is unknown", name1),
    }

    match get_favorite_fruit(name2) {
        Some(fruit) => println!("{}'s favorite fruit is {}", name2, fruit),
        None => println!("{}'s favorite fruit is unknown", name2),
    }
}
```

**Example 3: Matching Ranges**
```rust
fn main() {
    let score = 85;

    match score {
        0..=59 => println!("Failed"),
        60..=79 => println!("Passed"),
        80..=100 => println!("Excellent"),
        _ => println!("Invalid score"),
    }
}
```

**Example 4: Matching with Guards**
```rust
fn main() {
    let age = 25;
    let student = false;

    match age {
        0..=17 if !student => println!("Child"),
        0..=17 if student => println!("Student"),
        18..=65 => println!("Adult"),
        _ => println!("Senior Citizen"),
    }
}
```

Thanks for reading. Get me in [Twitter](https://x.com/ashsajal1), [Linkedin](https://linkedin.com/in/ashsajal)