Learn · 09

Pattern Matching

Use exhaustive match expressions over enums, Option, Result, literals, and wildcards to handle every case safely at compile time.

match is Ochre's primary branching construct for structured data. Unlike switch in C or JavaScript, match is an expression (it returns a value), never falls through between arms, and is exhaustiveness-checked by the compiler for enums, Option, and Result.

Matching Literals & Wildcards

Match integers, booleans, or strings, and use _ as a catch-all arm:

fn status_category(code: Int) -> Str {
    return match code {
        200 => "ok",
        201 => "created",
        404 => "not found",
        500 => "server error",
        _ => "other",
    }
}

fn main() {
    println(status_category(200))
    println(status_category(404))
    println(status_category(418))
}

Expected Output

ok
not found
other

Exhaustive Enum Matching

When you match on an enum without a _ wildcard, the type checker verifies that every variant is handled. If you later add a new variant to the enum, every incomplete match becomes a compile-time error instead of a silent bug:

enum LogLevel {
    Debug,
    Info,
    Warn,
    Error,
}

fn prefix(lvl: LogLevel) -> Str {
    return match lvl {
        LogLevel.Debug => "[DBG]",
        LogLevel.Info => "[INF]",
        LogLevel.Warn => "[WRN]",
        LogLevel.Error => "[ERR]",
    }
}

fn main() {
    println("{prefix(LogLevel.Info)} server booted")
    println("{prefix(LogLevel.Error)} timeout")
}

Expected Output

[INF] server booted
[ERR] timeout

Destructuring Option and Result

match binds the inner value of Some(v), Ok(v), and Err(e) directly in the arm scope:

fn format_lookup(v: Int?) -> Str {
    return match v {
        Some(n) => "found {n}",
        None => "missing",
    }
}

fn main() {
    let ports = #{ "http": 80, "https": 443 }
    println(format_lookup(ports["https"]))
    println(format_lookup(ports["ssh"]))
}

Expected Output

found 443
missing

Common Mistake: Non-Exhaustive match

enum Color {
    Red,
    Green,
    Blue,
}

fn label(c: Color) -> Str {
    return match c {
        Color.Red => "red",
        Color.Green => "green",
    }
}

The compiler immediately reports: non-exhaustive 'match' on enum 'Color': missing Blue.

Exercise

Create an enum Command with Ping, Echo(Str), and Quit. Write a run_cmd(c: Command) -> Str function using match and test all three variants in main().

Show Solution
enum Command {
    Ping,
    Echo(Str),
    Quit,
}

fn run_cmd(c: Command) -> Str {
    return match c {
        Command.Ping => "pong",
        Command.Echo(msg) => msg,
        Command.Quit => "bye",
    }
}

fn main() {
    println(run_cmd(Command.Ping))
    println(run_cmd(Command.Echo("hello ochre")))
    println(run_cmd(Command.Quit))
}