Pattern matching

match and case, binding patterns, exhaustiveness, and why there is no if let.

vlatest

match is a statement, not an expression: arms return values with an explicit return, they do not yield a value.

Shape

match (subject) {
    case pattern -> { ... }
    case pattern -> { ... }
    case _ -> { ... }
}
  • The subject goes in parentheses.
  • Each arm is case + pattern + -> + a braced body.
  • _ matches everything not matched above. There is no default keyword and no bare case -> arm, writing default -> is E0111 expected '?', found identifier 'default'.
  • case a, b -> lists alternative patterns for one arm.
  • case x if cond -> adds a guard.
fn grade(score: int) -> string {
    match (score) {
        case 100 -> { return "perfect" }
        case 0 -> { return "nothing" }
        case _ -> { return "somewhere" }
    }
}

some is a pattern, not a constructor

This is the single most common misunderstanding, so it is worth stating plainly: there is no some(x) function. some and none only appear in pattern position.

fn findFirst(items: List<int>) -> int? {
    for (i in items) {
        return i
    }
    return none
}

fn main() {
    let value = findFirst([42])
    match (value) {
        case some(v) -> { println("present: {v}") }
        case none -> { println("absent") }
    }
}

To build an optional, return the value where an optional is expected. The checker wraps it for you:

fn findFirst(xs: List<int>) -> int? {
    for (x in xs) {
        return x          // wrapped into `some(x)` automatically
    }
    return none
}
fn findFirst(items: List<int>) -> int? {
    for (i in items) {
        return i
    }
    return none
}

fn main() {
    match (findFirst([1])) {
        case some(v) -> { println("got {v}") }   // got 1
        case none -> { println("empty") }
    }
}

Writing some(x) in expression position is an undeclared-name error.

Empty arms

An empty arm is {}:

fn main() {
    let value: int? = 1
    match (value) {
        case some(v) -> { println(v) }
        case none -> {}
    }
}

Multiple values in one arm

Comma-separated patterns are alternatives. They may not bind names:

fn name(n: int) -> string {
    match (n) {
        case 1, 2, 3 -> { return "small" }
        case _ -> { return "big" }
    }
}

Exhaustiveness

match must cover every case of an enum, or the compiler rejects it. This is checked at compile time, which is the main safety benefit of the feature.

enum Colour {
    Red
    Green
    Blue
}

fn describe(c: Colour) -> string {
    match (c) {
        case Red -> { return "warm" }
        case Green -> { return "natural" }
        // `case Blue` is missing: this is a compile error
    }
}

Matching enums with payloads

An enum case that carries data is matched by giving the case name and binding each field:

enum Event {
    Key(c: char)
    Resize(w: int, h: int)
    Close
}

fn main() {
    let e = Event.Resize(800, 600)
    match (e) {
        case Event.Key(c) -> { println("key {c}") }
        case Event.Resize(w, h) -> { println("size {w}x{h}") }
        case Event.Close -> { println("bye") }
    }
}

A plain user enum is not the same as the built-in optional type T?. You do not need one for absence: T? plus match covers the same ground.

Matching collections

There are no list patterns. [one] and [] are syntax errors, a match arm cannot destructure a list or a map:

error[E0111] -- syntax error
    error: expected a pattern, found `[`

Reach for len and indexing instead, and branch on the length:

fn describe(parts: List<string>) -> string {
    let n = len(parts)

    if (n == 0) {
        return "empty"
    }
    if (n == 1) {
        return "one: {parts[0]}"
    }

    return "many: {n}"
}

fn main() {
    println(describe(["a", "b"]))     // many: 2
    println(describe(["solo"]))       // one: solo
}

To pull the first element out of a list, match the optional returned by indexing, or loop with for and break, both are covered under Optionals and Lists.

The _ pattern

_ matches anything and binds nothing:

fn main() {
    let value = 5
    match (value) {
        case 0 -> { println("zero") }
        case _ -> { println("something else") }
    }
}

Next steps