Rust Programming: match Control Flow Construct

0

The match control flow construct in Rust allows you to compare a value against a series of patterns and then execute code based on which pattern matches. For example, the following code uses match to determine the value in cents of a US coin:

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,

    }

}

The match expression first compares the value of coin to the pattern Coin::Penny. If the value of coin matches the pattern, the code associated with that pattern is executed, which in this case is the expression `1`. If the value of coin does not match the pattern Coin::Penny, the match expression then compares the value of coin to the pattern Coin::Nickel. If the value of coin matches the pattern Coin::Nickel, the code associated with that pattern is executed, which in this case is the expression `5`. This process continues until the match expression finds a pattern that matches the value of coin or until it has exhausted all of the patterns.

The code associated with each arm of the match expression is an expression, and the resultant value of the expression in the matching arm is the value that gets returned for the entire match expression. In the example above, the match expression will return the value 1 if the value of coin is Coin::Penny, the value 5 if the value of coin is Coin::Nickel, and so on.

The match control flow construct is a powerful tool that can be used to handle a wide variety of situations. It is especially useful when you need to compare a value against multiple patterns.

Post a Comment

0Comments
Post a Comment (0)