v0.4.0
Control flow · Lesson 3.12

Match

Source
Choose what to run by comparing one value against a list of arms, with | joining values that share an arm and _ for the rest.
You'll need: Else if

An else if chain that compares one value with a list of constants — if status == 200 … else if status == 404 … else if status == 500 … — repeats the same name in every condition, and the reader has to check each line to be sure it really is the same value. match says it once. It compares one value against a list of arms and runs the first arm whose pattern fits.

Arms and patterns

let count: int32 = 2;
match count {
    0 => PrintLine("none"),
    1 => PrintLine("one"),
    2 => PrintLine("a pair"),
    _ => PrintLine("several")
}

After match comes the value being examined, then the arms in braces. Each arm is pattern => what to do, and arms are separated by commas. The patterns here are literals — the arm 2 fits when count is 2.

How an arm is chosen

The arms are tried from the top. The first one that fits runs, and the rest are skipped — exactly like an else if chain. Whichever arm runs, the program then carries on after the match:

flowchart LR
    v(["`match count`"]) --> a0{"fits `0`?"}
    a0 -- "yes" --> r0["`none`"]
    a0 -- "no" --> a1{"fits `1`?"}
    a1 -- "yes" --> r1["`one`"]
    a1 -- "no" --> a2{"fits `2`?"}
    a2 -- "yes" --> r2["`a pair`"]
    a2 -- "no" --> a3{"fits `3` or `4`?"}
    a3 -- "yes" --> r3["`a few`"]
    a3 -- "no" --> e["anything else, `_`:<br/>`several`"]

The last arm may be _, which fits any value the arms above it did not name. It must come last — arms after it could never run. If you come from a language that spells the default else, the compiler stops you:

error: 'else' is not a match arm
help: use '_' for the default arm

Several values, one arm

Two values that share an outcome share an arm. Join them with |, and the arm fits either one:

match count {
    0 => PrintLine("none"),
    1 => PrintLine("one"),
    2 => PrintLine("a pair"),
    3 | 4 => PrintLine("a few"),
    _ => PrintLine("several")
}

An arm with a block

An arm that needs more than one statement takes a block in braces. The comma after a block arm is optional, but writing it keeps every arm alike:

match status {
    200 => PrintLine("ok"),
    404 => {
        PrintLine("not found");
        PrintLine("check the address");
    },
    _ => PrintLine("status {}", status)
}

Covering every value

A bool has only two values, so naming both covers everything, and no _ is needed:

match ready {
    true => PrintLine("ready"),
    false => PrintLine("not ready yet")
}

Every match must cover every value. An int32 has far more values than any list of arms can name, so a match on one without a _ arm is refused:

error: match on 'int32' is not exhaustive; its arms do not cover every value
help: add a '_' arm

When the other values really should do nothing, say so with an empty _ => {} arm:

let missed: int32 = 99;
match missed {
    1 => PrintLine("one"),
    2 => PrintLine("two"),
    _ => {}
}

The rule means a value can never slip through a match unnoticed: either an arm names it, or the _ arm says what to do with the rest.

What match checks for you

match is stricter than an else if chain in useful ways. A chain will happily run with a condition that can never be reached, or with no branch for some value, but match refuses both:

Mistakeelse if chainmatch
The same case written twicethe second is deaderror: duplicate pattern in match
A catch-all before other casesthe rest are deaderror: the default arm must be the last match arm
A value no case handlesnothing runs for iterror: match on 'int32' is not exhaustive; its arms do not cover every value

Later parts add richer patterns — characters, ranges such as 1..=9 =>, and guards that add a condition to an arm.

The program

The whole lesson is one package in the Examples repository. Its comments explain every step.

Src/Main.rux
// `match` compares one value against a list of arms and runs the first arm whose pattern fits.
// It says the same as an `if` / `else if` chain of `==` tests, but names the value once instead
// of repeating it in every condition.
//
// Each arm is `pattern => what to do`, and arms are separated by commas. The last arm may be
// `_`, which fits any value the arms above it did not name. The `else` some languages use is
// refused:
//
//     error: 'else' is not a match arm
//     help: use '_' for the default arm
//
// Two values that share an outcome share an arm: `3 | 4 =>` fits either one.
import Io::PrintLine;

func Main() -> int {
    // Literal patterns, alternatives joined by `|`, and `_` for everything else.
    let count: int32 = 2;
    match count {
        0 => PrintLine("none"),
        1 => PrintLine("one"),
        2 => PrintLine("a pair"),
        3 | 4 => PrintLine("a few"),
        _ => PrintLine("several")
    }

    // An arm that needs more than one statement takes a block.
    let status: int32 = 404;
    match status {
        200 => PrintLine("ok"),
        404 => {
            PrintLine("not found");
            PrintLine("check the address");
        },
        _ => PrintLine("status {}", status)
    }

    // A `bool` has only two values, so naming both covers everything and no `_` is needed.
    let ready = false;
    match ready {
        true => PrintLine("ready"),
        false => PrintLine("not ready yet")
    }

    // Every match must cover every value. An `int32` has far more values than two arms name, so
    // leaving out the `_` arm is refused:
    //
    //     error: match on 'int32' is not exhaustive; its arms do not cover every value
    //     help: add a '_' arm
    //
    // When the other values should do nothing, say so with an empty `_ => {}` arm.
    let missed: int32 = 99;
    match missed {
        1 => PrintLine("one"),
        2 => PrintLine("two"),
        _ => {}
    }
    PrintLine("99 fit no named arm, so that match did nothing");
    return 0;
}

Run it

cd Examples/ControlFlow/Match
rux run
a pair
not found
check the address
not ready yet
99 fit no named arm, so that match did nothing

Common mistakes

Try it yourself

  1. Write a match on an int32 day that prints the name of the day for 1 to 7 and "no such day" for anything else.
  2. Rewrite the status match as an else if chain and compare how often status is named.
  3. Change the _ => {} arm of the missed match so it prints the value, then set missed to 2 and run again.
  4. Write a second match on day that prints "weekend" for 6 | 7 and "weekday" for the rest.
  5. Write the same case twice in one match and read the error.

Learn more