Guides · 06

Pattern matching

A pattern describes the shape of a value and names the parts you want out of it. Patterns appear in five places: match arms, if bindings, shapeof tests, destructuring con declarations, and destructuring parameters. The rules are the same in all of them, so once you know them for one place you know them for all five.

Guide 05 introduces match, the comma rule for arms, and switch, which chooses by value instead of by shape. This guide is about the patterns themselves.

Binders

A pattern is a shape with slots. A slot that takes a value out is a binder, and the rule for binders is small: a binder is a name or _, optionally followed by : Type.

  • n binds the value in that slot to the name n. Its type is worked out from the slot.
  • _ matches anything and binds nothing.
  • n: T binds, and also requires the value to be a T. T can be the slot's own type, one member of a union, or one variant of an enum.
  • _: T requires a T without binding anything.
Vyi
import { println } from "@fmt"

enum Shape {
    Dot,
    Square(i32),      // side
    Rect(i32, i32),   // width, height
}

fn width(s: Shape) i32 {
    return match s {
        Dot:             0,
        Square(side):    side,
        Rect(w: i32, _): w,
    }
}

fn main() !u8 {
    println(width(Square(7)))    // prints 7
    println(width(Rect(3, 9)))   // prints 3
    println(width(Dot))          // prints 0
    return Ok(0)
}

Square(side) binds the payload as side. Rect(w: i32, _) binds the first element as w, checks that it is an i32, and skips the second.

Payload-less variants are written bare

A variant without a payload, such as Dot, is written by its bare name in every pattern position: at the head of a match arm, inside a slot, in an if binding, and in a shapeof test. Inside a slot, a bare name is that variant when the slot's type is an enum with a payload-less variant of that name. Any other name binds.

Vyi
import { println } from "@fmt"

enum Light { Red, Green }

fn canGo(light: ?Light) bool {
    return match light {
        Some(Green): true,
        Some(Red):   false,
        None:        false,
    }
}

fn main() !u8 {
    println(canGo(Some(Green)))   // prints true
    println(canGo(Some(Red)))     // prints false
    println(canGo(None))          // prints false
    return Ok(0)
}

?Light is a Light that might be missing: it holds Some(light) or None. Some(Green) matches a Some holding Green. Inside the slot, Green is the variant, not a new name. None follows the same rule as Green: it is an ordinary variant of Optional, which guide 07 covers.

When a slot holds a union of enums and two of them declare a variant with the same name, the bare name is ambiguous and the compiler rejects it. Name the enum, as in _: Fan.Off.

Pattern bindings are con

Every name a pattern binds is a con binding. There is no mut destructuring:

Vyi · does not compile
struct Point { x: i32, y: i32 }

fn main() !u8 {
    con p = Point{ x: 1, y: 2 }
    mut Point(x, y) = p   // error: destructuring binds immutably
    return Ok(0)
}

To change a value you took out with a pattern, copy it into a mut binding. A pattern only reads its subject. It never gives you a way to write into it.

Destructuring declarations

A con declaration can take a pattern where the name would go. A struct pattern takes fields by name, and can rename them or leave some out. Written with parentheses, it takes fields by position, in the order the struct declares them. A tuple pattern takes elements by position:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn main() !u8 {
    con p = Point{ x: 3, y: 4 }

    con Point{ x, y } = p
    con Point{ x: left } = p
    con Point(first, _) = p
    con (width, height) = (7, 5)

    println(x)        // prints 3
    println(y)        // prints 4
    println(left)     // prints 3
    println(first)    // prints 3
    println(width)    // prints 7
    return Ok(0)
}

Point{ x: left } binds the field x as left and ignores y. Point(first, _) binds the first field, x, as first.

A declaration has no "else" branch, so its pattern must match every value of its type. Such a pattern is irrefutable. A struct or tuple pattern is irrefutable when each of its parts is. A variant of an enum with more than one variant is not, and neither is a literal, at any depth. The compiler rejects a pattern that could fail:

Vyi · does not compile
fn first(opt: ?i32) i32 {
    con Some(n) = opt   // error: `opt` may still be `None` here
    return n
}

The message suggests the two ways out: test the value first, or use an if binding, which has somewhere to go when the pattern doesn't match.

Parameters destructure too. The pattern sits where the parameter name would:

Vyi
import { println } from "@fmt"

struct Size { width: i32, height: i32 }

fn area(Size(w, h): Size) i32 {
    return w * h
}

fn main() !u8 {
    println(area(Size{ width: 2, height: 3 }))   // prints 6
    return Ok(0)
}

A for loop's variable is a single name, not a pattern. To take each item apart, destructure it in the loop body. Here each item of the array cart is an Item with a name and a price:

Vyi
import { println } from "@fmt"

struct Item { name: [*con]u8, price: i32 }

fn main() !u8 {
    con cart = [2]Item[
        Item{ name: "pen", price: 2 },
        Item{ name: "book", price: 10 },
    ]
    mut total = 0
    for item in cart {
        con _{ price } = item
        total += price
    }
    println(total)   // prints 12
    return Ok(0)
}

_{ price } is a struct pattern whose struct type is worked out from item, the same way _{ ... } works for struct literals.

match arms

Variant patterns and literal slots

An arm over an enum names a variant, and parentheses destructure its payload. A slot can also hold a literal, which matches when the payload equals it. Arms are tried in order, so a specific value can get its own arm ahead of the general one:

Vyi
import { println } from "@fmt"

enum Cart { Empty, Items(i32) }

fn summary(c: Cart) [*con]u8 {
    return match c {
        Empty:    "empty",
        Items(1): "one item",
        Items(_): "several items",
    }
}

fn main() !u8 {
    println(summary(Items(1)))   // prints one item
    println(summary(Items(3)))   // prints several items
    println(summary(Empty))      // prints empty
    return Ok(0)
}

Items(1) covers only a cart of one item, so the arm Items(_) is still needed for every other count.

At the head of an arm, a name is always a variant (or, in match typeof, a type), never a binder. The arm names resolve against the subject's type, so Empty means Cart.Empty without writing the enum. That works the same for every enum, including the Some, None, Ok, and Err of Optional and Result.

Nested patterns

Patterns nest to any depth. A slot can hold another variant pattern, a struct pattern, or a tuple pattern, and one arm matches through every layer at once:

Vyi
import { println } from "@fmt"

enum Reading { Celsius(i32), Missing }
enum Sensor { Online(Reading), Offline }

fn temperature(s: Sensor) i32 {
    return match s {
        Online(Celsius(t)): t,
        default:            0,
    }
}

fn main() !u8 {
    println(temperature(Online(Celsius(21))))   // prints 21
    println(temperature(Offline))               // prints 0
    return Ok(0)
}

A struct pattern inside a variant takes fields straight out of the payload:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn main() !u8 {
    con spot: ?Point = Some(Point{ x: 6, y: 1 })
    match spot {
        Some(Point{ x }): println(x),   // prints 6
        None:             println("nowhere"),
    }
    return Ok(0)
}

Matching one variant of a payload

When a payload is itself an enum, the : Type of a binder can name one of that enum's variants. The arm then matches only when the payload is that variant. _: Interrupted checks without binding, and e: Closed checks and binds the error. For a payload-less variant, the bare name Err(Interrupted) says the same as Err(_: Interrupted). e: _ takes whatever is left:

Vyi
import { println } from "@fmt"

enum ReadError { Interrupted, Closed, Frozen }

fn describe(r: ReadError!i32) [*con]u8 {
    return match r {
        Ok(_):               "ok",
        Err(_: Interrupted): "try again",
        Err(e: Closed):      "closed",
        Err(e: _):           "failed",
    }
}

fn main() !u8 {
    println(describe(Ok(5)))             // prints ok
    println(describe(Err(Interrupted)))  // prints try again
    println(describe(Err(Frozen)))       // prints failed
    return Ok(0)
}

An arm like Err(_: Interrupted) covers only part of Err, and the compiler knows it. Without an arm for the rest, the match is rejected and the message names what is missing:

Vyi · does not compile
enum ReadError { Interrupted, Closed }

fn describe(r: ReadError!i32) [*con]u8 {
    return match r {   // error: missing Err(Closed)
        Ok(_):               "ok",
        Err(_: Interrupted): "try again",
    }
}

Multi-pattern arms

Patterns separated by commas before the : are alternatives that share one body (guide 05 shows them with switch too). Because only one alternative matches, a binder in one of them would have no value when another matched. Alternatives can't bind:

Vyi · does not compile
enum ParseError { Empty }

fn classify(r: ParseError!i32) i32 {
    match r {
        Ok(n), Err(_): return 1,  // error: matches without binding
    }
}

Type patterns: matching over a union

A union value such as i32 | Size holds a value of one of its member types, and it knows which one. match typeof u chooses an arm by that member type. An arm names a type, or gives a struct pattern that destructures the member directly. Inside a type arm, u itself has the matched type. Here a size is either a width and a height, or one number for a square:

Vyi
import { println } from "@fmt"

struct Size { width: i32, height: i32 }

fn area(u: i32 | Size) i32 {
    match typeof u {
        Size{ width, height }: return width * height,
        i32:                   return u * u,
    }
}

fn main() !u8 {
    println(area(Size{ width: 2, height: 3 }))   // prints 6
    println(area(4))                             // prints 16
    return Ok(0)
}

A type arm is an ordinary type expression, so a generic type such as Optional(i32) works as an arm as well as a plain name.

The typeof is required. A union's cases are its member types, so you select them through the value's type, not the value:

Vyi · does not compile
import { println } from "@fmt"

fn show(u: i32 | bool) {
    match u {   // error: a union value's members are selected
        i32:  println("number"),
        bool: println("flag"),
    }
}

Exhaustiveness

A match must handle every shape its subject can have:

  • Over an enum, every variant needs an arm. An arm with a literal slot, a nested pattern, or a : Variant binder covers only the part it names. With arms Ok(Some(v)) and Err(e), the case Ok(None) is still missing.
  • Over a struct or a tuple, which has only one shape, an arm that binds every slot covers everything, as in match p { Point{ x, y }: ... }. An arm that tests a literal, such as Point{ x: 0, y }, covers only part.
  • Over a union in match typeof, every member type needs an arm. That includes unions of single values such as 'a' | 'b' | 'q', where the compiler lists each missing value.
  • Over the open error type error (guide 07), no list of arms is complete, so a default arm is required.

An arm that the arms above it already cover can never run, and the compiler rejects it. Put the narrower arm first:

Vyi · does not compile
enum Cart { Empty, Items(i32) }

fn summary(c: Cart) [*con]u8 {
    return match c {
        Empty:    "empty",
        Items(_): "several items",
        Items(1): "one item",   // error: this arm can never match
    }
}

The catch-all arm is spelled default. _ is not an arm: it is a binder that discards, and at the head of an arm the compiler reads it as a type to work out from the code around it, which fails:

Vyi · does not compile
enum Color { Red, Green, Blue }

fn hue(c: Color) i32 {
    return match c {
        Red: 1,
        _:   0,   // error: cannot infer match arm type
    }
}

A value with no shape to select on, such as an integer or a string, is not a match subject. You choose by its value with switch, which has its own coverage rule (guide 05).

if bindings

if Pattern = subject { ... } else { ... } runs the first block when the pattern matches, with its binders in scope. When it doesn't match, the else block runs, or nothing does if there is no else:

Vyi
import { println } from "@fmt"

fn orDefault(o: ?i32) i32 {
    if Some(v) = o {
        return v
    } else {
        return 99
    }
}

fn main() !u8 {
    println(orDefault(Some(33)))   // prints 33
    println(orDefault(None))       // prints 99
    return Ok(0)
}

Everything a match arm accepts works here: nested patterns such as if Online(Celsius(t)) = s, struct patterns, and payload-less variants written bare:

Vyi
import { println } from "@fmt"

enum Color { Red, Green, Blue }

fn isGreen(c: Color) bool {
    if Green = c { return true }
    return false
}

fn main() !u8 {
    println(isGreen(Green))   // prints true
    println(isGreen(Blue))    // prints false
    return Ok(0)
}

shapeof

When all you need is a bool that says whether a value matches, write Pattern shapeof value. A shapeof pattern can't bind names, so use _ for the slots:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con o: ?i32 = Some(1)
    println(Some(_) shapeof o)   // prints true
    println(None shapeof o)      // prints false
    return Ok(0)
}

Guards, chains, and if as a value

A ; guard after the subject adds a condition. The binders are in scope in the guard and in the block. The block runs only when the pattern matches and the guard holds. else if chains work as with any if:

Vyi
import { println } from "@fmt"

fn ageGroup(age: ?i32) [*con]u8 {
    return if Some(years) = age; years >= 18 {
        "adult"
    } else if Some(years) = age {
        "minor"
    } else {
        "unknown"
    }
}

fn main() !u8 {
    println(ageGroup(Some(30)))   // prints adult
    println(ageGroup(Some(9)))    // prints minor
    println(ageGroup(None))       // prints unknown
    return Ok(0)
}

The first branch needs both a Some and an age of at least 18. Some(9) matches the pattern but fails the guard, so it falls to the second branch.

As the example shows, an if binding works in value position like any other if: each branch gives its last expression.

At the top level of an if binding, a binder with : Type tests the subject itself. Over a union, if v: i32 = u matches when u holds an i32 and binds it as v. Over a union of single values, it tests the value:

Vyi
import { println } from "@fmt"

fn asNumber(u: i32 | bool) i32 {
    return if v: i32 = u { v } else { 0 }
}

fn delay(mode: "fast" | "slow") i32 {
    return if s: "slow" = mode { 20 } else { 1 }
}

fn main() !u8 {
    println(asNumber(99))       // prints 99
    println(asNumber(true))     // prints 0
    println(delay("slow"))      // prints 20
    return Ok(0)
}

Narrowing

A successful match also tells the compiler something about the subject, and the compiler uses it. Inside a match typeof arm, the subject has the matched member type. That is why u * u type-checks as integer multiplication in the area example above.

The same knowledge flows through the rest of a function. After an early return, a binding holds only what is left. That works for the variants of an enum as well as for the members of a union. A binding's initial value, and each assignment to a mut binding, narrow it too:

Vyi
import { println } from "@fmt"

fn double(o: ?i32) i32 {
    if o == None { return 0 }
    return match o {
        Some(n): n * 2,
    }
}

fn main() !u8 {
    println(double(Some(5)))   // prints 10
    println(double(None))      // prints 0
    return Ok(0)
}

After if o == None { return 0 }, o can only hold Some, so the match needs no None arm.

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut v: i32 | bool = 1
    println(v + 1)   // prints 2
    v = false
    println(!v)      // prints true
    return Ok(0)
}

v holds an i32 until the assignment, so v + 1 is integer addition. After v = false, v holds a bool, so !v compiles.

Where paths that left a mut binding with different contents meet again, such as after an if or at the top of a loop that changes it, the binding holds whatever any of those paths left. Once you take its address, anything may write it, so the compiler reads it at its declared type from then on.

Unions of single values narrow by value, and each test narrows further:

Vyi
import { println } from "@fmt"

fn third(x: 3) i32 { return 30 }

fn pick(n: 1 | 2 | 3) i32 {
    if n == 1 { return 10 }
    if v: 2 = n { return 20 }
    return third(n)
}

fn main() !u8 {
    println(pick(1))   // prints 10
    println(pick(2))   // prints 20
    println(pick(3))   // prints 30
    return Ok(0)
}

After the first test, n is 2 | 3. After the second, it can only be 3, so passing it to third, which accepts exactly 3, compiles.

Narrowing stays inside one function body. A parameter starts at its declared type, whatever the caller knew, and a file-level variable stops being narrowed at the next function call. The full rules are in patterns: narrowing.

See also: reference/patterns.