Pattern Matching
The match expression compares a value against a series of patterns and
evaluates the branch of the first pattern that matches. It is an expression,
so it produces a value that can be assigned to a variable.
Basic Match
Match a value against literal patterns:
let label = match x {
1 => "one"
2 => "two"
3 => "three"
_ => "other"
}Each arm consists of a pattern followed by => and a result expression.
Arms are evaluated in order and the first match wins.
Wildcard Pattern
The _ pattern matches any value. It serves as the default or catch-all
case and is typically placed last:
let description = match status {
200 => "ok"
404 => "not found"
500 => "server error"
_ => "unknown"
}Guard Expressions
Match arms can include a guard clause using if to add a condition.
The arm only matches when both the pattern and the guard are satisfied:
match x {
1 if y > 0 => "positive one"
1 if y < 0 => "negative one"
1 => "one with zero y"
_ => "other"
}Guards are useful when the same pattern needs different results depending on other state.
Match as Expression
Since match is an expression, it can be used anywhere a value is expected:
// Assign the result to a variable
let category = match age {
0 => "newborn"
12 => "child"
18 => "teenager"
_ => "adult"
}// Assign match result then use in a template string
let status_code = match code {
200 => "ok"
_ => "error"
}
let msg = `Status: ${status_code}`// Return from a function
function classify(n) {
return match n % 2 {
0 => "even"
_ => "odd"
}
}Multiple Statements in Arms
When an arm needs to execute multiple statements, wrap them in braces. The value of the arm is the last expression in the block:
let result = match input {
0 => 0
_ => {
let doubled = input * 2
doubled + 1
}
}Practical Examples
Command Dispatch
let output = match command {
"help" => show_help()
"version" => show_version()
"run" => run_script(args)
_ => error("unknown command: %s", command)
}Type-Based Handling
let description = match type(value) {
"int" => "an integer"
"string" => "a string"
"list" => "a list"
"map" => "a map"
_ => "something else"
}Range Classification
function http_status(code) {
if (code >= 500) {
"server error"
} else if (code >= 400) {
"client error"
} else if (code >= 300) {
"redirect"
} else if (code >= 200) {
"success"
} else {
"informational"
}
}