Rust Notes #2: Match Guards and @ Bindings

Rust Notes #2: Match Guards and @ Bindings

After finishing The Rust Programming Language, I know a lot more Rust concepts, but am still learning to put them into practice. Two useful pattern matching concepts are match guards and bindings.

Match Guards

Match guards add conditions to match arms:


match (2, 2) {
  (x, y) if x == y {
    println!("Match!");
  },
  (x, y) {
    println!("Just a tuple");
  }
}

This feature allows you to add greater specificity or conditionality to patterns in match statements, which can be useful for handling subtle cases. See Rust By Example.

@ Bindings

Bindings inside match expressions let the programmer create a variable that will hold a value while testing that it matches some pattern.

Here is a variation on the example given in the documentation:

match transaction {
    Transaction::Deposit { amount: amount_variable @ 3...7 } => {
        println!("Deposit was between 3 and 7: {}", amount_variable )
    },
    Transaction::Deposit { amount: 10...12 } => {
        // Note we're not using the variable, just testing it here
        println!("Deposit was between 10 and 12")
    },
    Transaction::Deposit { amount } => {
        // Just use the value directly
        println!("Transaction was for {}", amount)
    },
}

Overall, the pattern matching functionality in Rust turns out to be one of my favorite features.

Published
About WorkNow