DEV Community

Abbas Ogaji
Abbas Ogaji

Posted on

1

Learning Rust : Match Statements

Rust has an extremely powerful control flow operator called match that allows you to compare a value against a series of patterns and then execute code based on which pattern matches. Patterns can be made up of literal values, variable names, wildcards, and many other things; (source)

Match statement are kind of similar to switch statements; below is an example of how to use a match statements in rust

    let country_code = 234;
    let country = match country_code{
        44 => "United Kingdom",
        234 => "Nigeria",
        7 => "Russia",
        1 => "USA",
        _ => "Unknown"
    };
    println!("the country with code {} is {}", country_code, country)
Enter fullscreen mode Exit fullscreen mode
OUTPUT: "the country with code 234 is Nigeria"
Enter fullscreen mode Exit fullscreen mode

The Breakdown;

  • 1) The match control flow operation begins with the match keyword followed by the value or variable used for comparison.
  • 2) After the keyword and variable is the expression. the match expressions are encapsulated within curly brackets.
  • 3) In the expression, the left hand side is the pattern and the right hand side is the code executed when the pattern matches, here we are returning a string value.

  • Notice the _ pattern at the bottom?. The _ pattern is a special pattern that will match any value. By putting it after our other arms, the _ will match all the possible cases that aren’t specified before it.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay