Pattern matching
A pattern tests a value’s shape and names the parts inside it.
Match expressions
Section titled “Match expressions”match checks a value against each arm in order. The first arm that matches runs, and its result becomes the value of the match.
fn describe(n: int) -> string { match n { 0 => "zero", 1 => "one", _ => "many", }}Exhaustiveness
Section titled “Exhaustiveness”A match must cover every possible value. The compiler rejects a match that misses a case:
enum Color { Red, Green, Blue }
fn name(color: Color) -> string { match color { Color.Red => "red", Color.Green => "green", }} ✕ match is not exhaustive ╭─[example.lis:4:3] 3 │ fn name(color: Color) -> string { 4 │ match color { · ─────┬───── · ╰── not all patterns covered 5 │ Color.Red => "red", ╰──── help: Handle the missing case Color.Blue, e.g. Color.Blue => { ... } · code: [infer.non_exhaustive]Matchable patterns
Section titled “Matchable patterns”Literals
Section titled “Literals”Integer, boolean, string, and rune literals match exact values:
fn http_code(status: string) -> int { match status { "ok" => 200, "missing" => 404, _ => 500, }}fn answer(key: rune) -> string { match key { 'y' => "yes", 'n' => "no", _ => "unknown", }}Bindings
Section titled “Bindings”An identifier binds the matched value to a name:
fn print_age(ages: Map<string, int>, name: string) { match ages.get(name) { Some(age) => fmt.Println(f"{name} is {age}"),value inside Some None => fmt.Println(f"{name} not found"), }}_ matches any value without binding it:
fn listen(input: string) { match strconv.Atoi(input) { Ok(port) => fmt.Println(f"listening on {port}"), Err(_) => fmt.Println(f"invalid port: {input}"),matches any error without binding it }}Tuples
Section titled “Tuples”Tuple patterns destructure by position:
fn locate(pair: (int, int)) -> string { match pair { (0, 0) => "origin", (x, 0) => f"on x-axis at {x}", (0, y) => f"on y-axis at {y}", (x, y) => f"at ({x}, {y})", }}Structs
Section titled “Structs”Struct patterns match fields by name:
struct Point { x: int, y: int,}
fn locate(point: Point) -> string { match point { Point { x: 0, y: 0 } => "origin", Point { x, y: 0 } => f"on x-axis at {x}", Point { x, y } => f"at ({x}, {y})", }}Use .. to ignore remaining fields:
struct User { name: string, email: string, age: int,}
fn greet(user: User) -> string { match user { User { name: "", .. } => "hello, stranger",ignores email and age _ => f"hello, {user.name}", }}Enum variants
Section titled “Enum variants”Enum patterns match variants and destructure their payloads:
enum Message { Ready, Write(string), Move { x: int, y: int },}
fn describe(msg: Message) -> string { match msg { Message.Ready => "ready", Message.Write(text) => f"writing: {text}", Message.Move { x, y } => f"moving to ({x}, {y})", }}Inside a match arm, the enum qualifier can be omitted:
fn describe(msg: Message) -> string { match msg { Ready => "ready",short for Message.Ready Write(text) => f"writing: {text}", Move { x, y } => f"moving to ({x}, {y})", }}Slices and arrays
Section titled “Slices and arrays”Bracketed patterns match slice and array elements:
fn summarize(items: Slice<int>) -> string { match items { [] => "empty", [n] => f"single: {n}", [first, second] => f"pair: {first}, {second}", [first, ..rest] => f"first is {first}, {rest.length()} more",Slice<int> }}The rest pattern ..rest captures the remaining elements. On a slice it gives a Slice, and on an array an Array. The rest pattern must come last:
fn last(items: Slice<int>) -> int { match items { [..rest, last] => last,error: elements after rest pattern are not supported _ => 0, }}Use .. without an identifier to ignore the rest:
fn first_or_zero(items: Slice<int>) -> int { match items { [first, ..] => first,ignores all remaining elements [] => 0, }}Or-patterns
Section titled “Or-patterns”An or-pattern uses | to join several alternatives in one arm:
fn axis(direction: Direction) -> string { match direction { North | South => "north-south", East | West => "east-west", }}Alternatives can bind variables if all of them bind the same names:
enum Event { KeyDown(rune), KeyUp(rune),}
fn describe(event: Event) -> string { match event { KeyDown(key) | KeyUp(key) => f"key: {key}",rune }}An or-pattern can also appear inside another pattern:
fn size(n: Option<int>) -> string { match n { Some(1 | 2) => "small", Some(_) => "large", None => "none", }}as for value capture
Section titled “as for value capture”Use as to capture the entire matched value:
fn track(history: Slice<Message>, msg: Message) -> Slice<Message> { match msg { Move { .. } as moved => history.append(moved),Message _ => history, }}To capture an or-pattern, wrap it in parentheses:
fn tag(event: Event) -> (rune, Event) { match event { (KeyDown(key) | KeyUp(key)) as pressed => (key, pressed),Event }}Pattern guards
Section titled “Pattern guards”Add if after a pattern to require an additional condition:
fn sign(opt: Option<int>) -> string { match opt { Some(n) if n > 0 => "positive", Some(_) => "non-positive", None => "empty", }}A guard and as can appear in the same arm:
fn positive(opt: Option<int>) -> Option<int> { match opt { Some(n) as found if n > 0 => found,Option<int> _ => None, }}Guards do not count toward exhaustiveness. If all arms have guards, a wildcard or catch-all arm is still required.
let else
Section titled “let else”let else binds a pattern that can fail to match. When the pattern does not match, the else branch runs. The else branch must return, break, continue, or panic.
fn greet(names: Map<int, string>, id: int) -> string { let Some(name) = names.get(id) else { return "unknown user" } f"hello, {name}"}A slice pattern that constrains the length can fail, because a slice has no fixed length:
fn run(args: Slice<string>) { let [_, command, ..] = args else { fmt.Println("usage: tool <command>") return } fmt.Println(f"running {command}")}