Pattern Matching Support by Language

Rust

Widely considered the gold standard for pattern matching in modern systems programming. It is exhaustive (the compiler forces you to handle every case) and expression-based (it returns a value).

Rust

match msg {
    Message::Quit => quit(),
    Message::Move { x, y } => move_cursor(x, y),
    Message::Write(text) => println!("{}", text),
    _ => {}, // Catch-all required if not exhaustive
}

Example: Result Type Pattern Matching

enum Result {
    Ok(i32),
    Err(String),
}

fn describe(r: Result) -> String {
    match r {
        Result::Ok(n)    => format!("Got number: {}", n),
        Result::Err(msg) => format!("Error: {}", msg),
    }
}

Haskell & OCaml

The pioneers of the feature. In these functional languages, pattern matching is not just a tool; it is the primary way you define functions.

Haskell Example

data Result = Ok Int | Err String

describe :: Result -> String
describe r =
  case r of
    Ok n    -> "Got number: " ++ show n
    Err msg -> "Error: " ++ msg

OCaml Example