SoFunction
Updated on 2025-03-10

Detailed explanation of the match expression in rust

Use match

Provides an extremely powerful control flow operator in rustmatch

  • matchAllow a value to match a series of patterns and execute the code corresponding to the matching pattern.
  • These modes can beSub-face valueVariable nameWildcardetc.

Let's have an example

fn main() {
    println!("penny {}", value_in_cents(Coin::Penny)) // penny 1
}
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 => {
            println!("There are multiple lines that require curly braces");
            25
        },
    }
}

Bound value mode

The matching branch can be bound to the part of the value of the matched object, so we canenumGet the value in the variant

fn main() {
    println!("penny {}", value_in_cents(Coin::Quarter(UsState::Alabama))) // State quarter from Alabama\n penny 25 
}
#[derive(Debug)]
enum UsState {
    Alabama,
    Alaska,
}
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState),
}
fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        // Pattern matching of bound values        Coin::Quarter(state) => {
            println!("State quarter from {:?}", state);
            25
        },
    }
}

In rust match match, all variants must be exhaustive

But ifmatchTo matchVariantsThere are too many, what should we do if we don’t want to deal with so many?

  • Wildcards can be used_Replace the remaining unlisted values
fn main() {
    let v = 0u8;
    match v {
        1 => println!("one"),
        2 => println!("two"),
        3 => println!("three"),
        // If you don't want to match, you can use `_` instead. The lower line change wildcard can only be placed on the last line        _ => println!("other")
    }
}

match syntax sugar [if let]

The above example can be usedif letControl flow for rewriting

fn main() {
    let v = 0u8;
    match v {
        1 => println!("one"),
        2 => println!("two"),
        3 => println!("three"),
        // If you don't want to match, you can use `_` instead. The lower line change wildcard can only be placed on the last line        _ => println!("other"),
    }
    // You can use let for abbreviation    if let 3 = v {
        println!("three");
    } else {
        println!("other")
    }
}

Let's summarizeif letThe role of

  • Handle only cares about one match two ignores other matches
  • Less code, less indentation, less template code
  • Give up the possibility of exhaustion
  • We canif letAs if it ismatchSyntax sugar

Match Option

fn main() {
    let five = Some(5);
    let six = plus_one(five);
    let none = plus_one(None);
    // Use pattern matching and Option to avoid NPE problems in other languages    match six {
        Some(value) => println!("six: {}", value),
        None => println!("six: None"),
    }
    match none {
        Some(value) => println!("none: {}", value),
        None => println!("none: None"),
    }
}
fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1)
    }
}

This is all about this article about match expressions in rust. For more relevant rust match expression content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!