Pattern matching

The match expression dispatches on values and destructures Results and enums.

Basic match

cleat
let msg = match status {
    200 => "ok",
    404 => "not found",
    500 => "server error",
    _ => "unknown",
}

Every match must be exhaustive — the _ wildcard catches unmatched values.

Result matching

cleat
match fetch("https://example.com") {
    Ok(body) => io.println(body),
    Err(e) => io.println("failed: ${e}"),
}

The Ok(v) and Err(e) patterns destructure the Result and bind the inner value.

Enum matching

cleat
let label = match severity {
    Severity.Low => "minor",
    Severity.Medium => "moderate",
    Severity.High => "urgent",
    Severity.Critical => "emergency",
}

Match with guards

The if keyword adds a condition after a pattern:

cleat
match result {
    Ok(n) if n > 90 => "excellent",
    Ok(n) if n > 70 => "good",
    Ok(_) => "passing",
    Err(e) => "error: ${e}",
}

Condition-only match

Omit the subject to match on arbitrary conditions:

cleat
let grade = match {
    score > 90 => "A",
    score > 80 => "B",
    score > 70 => "C",
    _ => "F",
}

Block bodies

Match arms can contain multiple statements. The last expression is the arm's value:

cleat
let exit_code = match run_agent() {
    Ok(result) => {
        io.println("Success: ${result}")
        0
    },
    Err(e) => {
        io.println("Failed: ${e}")
        1
    },
}

Match as expression

Match is an expression — it produces a value:

cleat
let message = match user.role {
    "admin" => "full access",
    "viewer" => "read only",
    _ => "restricted",
}

return match result {
    Ok(v) => v,
    Err(_) => 0,
}
Edit this page on GitHub