DEV Community

Cover image for Rust match Statement
Ashfiquzzaman Sajal
Ashfiquzzaman Sajal

Posted on

Rust match Statement

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:

fn main() {
    let number = 7;

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

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:

fn main() {
    let number = 3;

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

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:

fn main() {
    let number = Some(7);

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

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

Example code:

fn main() {
    let number = Some(7);

    match number {
        Some(_) => println!("Found a number"),
        None => println!("No number found"),
    }
}
Enter fullscreen mode Exit fullscreen mode

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

Example code:

fn main() {
    let age = 18;

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

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

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);
}
Enter fullscreen mode Exit fullscreen mode

Example 2: Matching Option Values

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),
    }
}
Enter fullscreen mode Exit fullscreen mode

Example 3: Matching Ranges

fn main() {
    let score = 85;

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

Example 4: Matching with Guards

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"),
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading. Get me in Twitter, Linkedin

Top comments (1)

Collapse
 
ashsajal profile image
Ashfiquzzaman Sajal

Don't forget to share your thoughts about match in comment.