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).
Enums. Rust Enums can hold data, allowing you to safely unwrap complex states without null checks.match for full checking, if let for single cases.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
}
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),
}
}
match r must cover all variants and each arm returns a String, so describe is purely the value of the match expression.[1]n or msg directly.[2]The pioneers of the feature. In these functional languages, pattern matching is not just a tool; it is the primary way you define functions.
data Result = Ok Int | Err String
describe :: Result -> String
describe r =
case r of
Ok n -> "Got number: " ++ show n
Err msg -> "Error: " ++ msg
case r of ... is an expression that returns a String for every pattern, so it can be used wherever a value is needed.[3]Ok n and Err msg destructure the value and bind fields directly in each branch.[4]