andersch.dev

<2025-04-19 Sat>

Pattern matching

Pattern matching is a mechanism in programming for checking a value against predefined patterns and executing code based on the match. Code using pattern matching rather than simple equality checks can often be more versatile and readable.

Languages with pattern matching include Rust (match expressions), Python (match-case statements), C# and Haskell.

Examples (Python, Rust)

def describe_value(value):
    match value:
        case 0:
            return "Zero"
        case n if n < 0:
            return "Negative"
        case _:
            return "Positive"
fn main() {
   let value = Some(5);

   match value {
       Some(n) if n > 3 => println!("Found a number greater than 3: {}", n),
       Some(n)          => println!("Found a number: {}", n),
       None             => println!("No number found"),
   }
}