DEV Community

loading...

Learning Rust : Match Statements

abbasogaji profile image Abbas Ogaji ・1 min read

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.

Discussion (0)

pic
Editor guide