What is Rust Match Control Flow Operator?

 What is Rust Match Control Flow Operator?

What is Rust Match Control Flow Operator?

The “Match” Control Flow Operator

  • Patterns may be made up of literal values, variable names, wildcards, and many other things.

Let’s Talk About Coin-Sorting Machine!
What is The Match Control Flow Operator in Rust?

Coins slide down a track with randomly sized holes along it, and each coin falls through the first hole it encounters that it fits into. 

Code It:

enum Coin {

    Penny,

    Nickel,

    Dime,

    Quarter,

}


fn value_in_cents(coin: Coin) -> u8 {

    match coin {

        Coin::Penny => 1,

        Coin::Nickel => 5,

        Coin::Dime => 10,

        Coin::Quarter => 25,

    }

}

In the same way as the coin sorting machine works, values go through each pattern in a match, and at the first pattern the value “fits,” the value falls into the joined code block to be executed during execution.
Let’s Break Down “Match”

fn value_in_cents(coin: Coin) -> u8 {

    match coin {

        Coin::Penny => {

            println!(“Lucky penny!”);

            1

        },

        Coin::Nickel => 5,

        Coin::Dime => 10,

        Coin::Quarter => 25,

    }

}

We list first the match keyword followed by an expression, which in this case is the value coin. The type of coin in this example is the Coin enum that we defined in function parameter.Next are the match arms. The arm has two parts: a pattern and some code. The first arm having a pattern which is the value Coin::Penny and then the => operator that separates the pattern and the code to run. In this case the code is just the value 1. Each arm is subtracted from the upcoming with a comma.When the match expression executes, it compares the resulting value against the pattern of each arm, in order. The code associated with that pattern is executed if a pattern matches the value. Execution continues to the next arm if that pattern doesn’t match the value, much as in a coin-sorting machine. We can have as many arms as we need, our match has four arms.

The code is connected and joined with every arm is an expression, and the resulting value of the expression in the matching arm is the value that gets returned for the entire match expression.

Why don’t we use “If”?

Because the expression with “ If ” needs to return a boolean value but with “Match”, it can be any type…

Curly Brackets in Match Arm:

fn value_in_cents(coin: Coin) -> u8 {

    match coin {

        Coin::Penny => 1,

        Coin::Nickel => 5,

        Coin::Dime => 10,

        Coin::Quarter(state) => {

            println!(“State quarter from {:?}!”, state);

            25

        },

    }

}


Typically the curly brackets aren’t used if the match arm code is short, as it was in the last example where each arm just returns a value. If we want to run multiple lines of code in a match arm, you can use curly brackets.

Patterns That Bind to Values:

At another useful aspect of match arms is that they may bind to the parts of the values that match the pattern. We can extract values out of enum variants.

Example

enum UsState {

    Alabama,

    Alaska,

    // –snip–

}


enum Coin {

    Penny,

    Nickel,

    Dime,

    Quarter(UsState),

}

From last example, let’s change one of our enum variants to hold data inside it. The United States minted quarters with different designs for each of the 50 states on one side from 1999 through 2008, The only quarters have this extra value as no other coins got state designs.We can add this information to our enum by changing the Quarter variant to include a UsState value stored inside it.

Let’s assume that a friend of ours is trying to collect all 50 state quarters.During we sort our loose change by coin type, we’ll also call out the name of the state connected with every quarter so if it’s one our friend doesn’t have, they can add it to their collection.

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter(state) => {
            println!(“State quarter from {:?}!”, state);
            25
        },
    }
}

We put a variable called state to the pattern that matches values of the variant in the match expression for this code, Coin::Quarter. The state variable would bind to the value of that quarter’s state. We can then use state in the code for that arm when a Coin::Quarter matches.
What if we Call a Particular State!

If we were to call value_in_cents(Coin::Quarter(UsState::Alaska)),

coin would be  Coin::Quarter(UsState::Alaska).


None of them match until we reach Coin::Quarter(state) when we compare that value with each of the match arms. The binding for state will be the value UsState::Alaska at that point.We can then use that binding in the println! thus the expression that getting the inner state value out of the Coin enum variant for Quarter.

Matching With Option<T>:

When we talked about the Option<T>, we wanted to get the inner T value out of the “Some” case when using Option<T>; we can also handle Option<T> using match as we did with the Coin enum! we’ll compare the variants of Option<T> instead of comparing coins, but the way that the match expression works remains the same.

Example

Let’s write a function that takes an Option<i32> and, if there’s a value inside, adds 1 to that value.The function should return the None value and not attempt to perform any operations iff there isn’t a value inside.

fn plus_one(x: Option<i32>) -> Option<i32> {

    match x {

        None => None,

        Some(i) => Some(i + 1),

    }

}


let five = Some(5);

let six = plus_one(five);

let none = plus_one(None);

The _ pattern will match any value. By keeping it after our other arms, the _ will match all the possible cases that aren’t specified before it. The () is only the unit value, so nothing will happen in the _ case. As a result, we can say that we want to do nothing for all the possible values that we don’t list before the _ placeholder.



 




Leave a Comment