v0.4.0

Patterns

A pattern describes the shape of a value. Matched against a value, it either fits or does not, and when it fits it may bind names to parts of the value. Patterns appear in these places:

PlacePatterns allowed
a match armevery form on this page
a catch armpatterns over the error — see Handling errors
a binding is testevery form on this page — see Type tests
a let or var bindingirrefutable forms only — see Destructuring
a for loop variableirrefutable forms only — see Loops

A pattern is irrefutable when it fits every value of its type — a name, _, and tuples and structures built from them — and refutable otherwise.

FormExampleFits
literal0, -1, 1.5, 'A', true, null, "go"a value equal to the literal
range1..5, 1..=9a number in the range
bindingnanything, and binds it to n
wildcard_anything, and binds nothing
tuple(0, y)a tuple whose elements fit
structurePoint { x: 0, y }a structure whose named fields fit
enum member.Red, Color::Redthat member
variant case.Round(r), .Gauge { level }that case, with a payload that fits
typedc: Circle, _: Squarea sum whose active member has that type
absencenonean absent optional
presence.Some(n), .Some(.Some(n))a present optional whose value fits
alternatives.Red | .Green, 0 | 1a value any of the alternatives fits
guardedn if n > 100a value the pattern fits and for which the guard holds

Patterns nest: wherever a pattern appears inside another — a tuple element, a field, a payload — any form can be used.

Literal patterns

An integer, floating-point, character or bool literal fits a value equal to it. A negative integer is written with its sign, -1. The literal takes the subject's type, so 255 fits a uint8 field and 'a' a char32; a literal of another kind is refused:

error: pattern has type 'char32', but the matched value has type 'int32'

null fits a null pointer:

func Read(p: *int32) -> int32 {
    return match p {
        null => 0,
        _ => unsafe { *p }
    };
}

A string literal fits a char8[..] holding the same characters: the lengths agree, then every byte does. This is how a word is matched, although == is not defined on slices:

func Command(word: char8[..]) -> int {
    return match word {
        "start" => 1,
        "stop" => 2,
        _ => 0
    };
}

A negative floating-point literal cannot be written as a pattern; use a guard.

Range patterns

A range pattern fits a number between two literal bounds. lo..hi excludes the upper bound; lo..=hi includes it. ..= is the only inclusive spelling: 1...9 is error: '...' is not a range operator, with help: use '..='.

func Classify(n: int32) -> char8[..] {
    return match n {
        -1 => "minus one",
        0 => "zero",
        1..5 => "one to four",
        5..=9 => "five to nine",
        _ => "other"
    };
}

Both bounds are needed: 5.. is error: expected a range pattern end after '..' before '=>'. Ranges apply to integers, floating-point numbers and every character width. For example, 'a'..='z' matches a lowercase ASCII scalar for a char32 subject or any wider one; a char8 or char16 subject needs bounds of its own width, such as c8'a'..=c8'z'.

Binding patterns

A name fits any value and binds it, for the rest of the arm. A binding is immutable, like a let:

let m = match pair {
    (a, b) if a > b => a,
    (_, b) => b
};

A bare name always binds; it never compares. A name that already names a constant, a type, a function or a case of the matched type cannot be used:

error: pattern 'Limit' cannot bind a new variable because 'Limit' already names a constant
  help: a pattern compares with literal values; write the value of 'Limit', or bind the value and compare it with 'Limit' in a guard such as 'value if value >= Limit'

The wildcard

_ fits anything and binds nothing. It skips a part inside a larger pattern, such as a tuple element or a payload: .Round(_) matches the case without naming its value. As a whole arm, _ => is the default arm, which must come last (see match).

Tuple patterns

A tuple pattern has one pattern per element, in order, and fits when every element fits:

func Classify(pair: (int32, int32)) -> int32 {
    return match pair {
        (0, 0) => 0,
        (x, 0) => 100 + x,
        (0, y) => 200 + y,
        (a, b) => a * 10 + b
    };
}

The number of elements must match the tuple's: error: tuple pattern has 3 elements, but matched tuple has 2. A tuple pattern whose every part is a binding or _ matches every value, so it covers the subject and makes any later arm unreachable.

Structure patterns

A structure pattern names the type and lists fields by name, in any order. field: pattern tests the field; field alone binds it to a variable of the same name. Fields left out are not tested:

match point {
    Point { x: 0, y: 0 } => PrintLine("origin"),
    Point { x: 0, y } => PrintLine("on the y axis at {}", y),
    Point { y: 7 } => PrintLine("at height 7"),
    _ => PrintLine("elsewhere")
}

The literals in field patterns compare at the field's type. A field the type does not have is error: struct 'Point' has no field 'z'. A structure pattern names only fields visible where it is written: a private field of another package's structure is refused, though the pattern may leave it out.

Every part of a tuple or structure pattern is tested, left to right, before any binding is set, so a pattern that fails binds nothing, and a guard sees the bindings of its own pattern.

Enum and variant patterns

A member of an enum is written in full, Color::Red, or with a leading dot, .Red, which takes the enum from the subject's type. A variant case is written the same way, followed by patterns for its payload — in parentheses for a positional case, in braces for a case with named fields:

variant Reading {
    Missing,
    Gauge { level: int32; unit: char32; },
    Pair(int32, int32)
}
func Level(r: Reading) -> int32 {
    return match r {
        .Missing => 0,
        .Gauge { level: 0 } => -1,
        .Gauge { level, unit: 'C' } => level,
        Reading::Gauge { level: l } => l * 10,
        .Pair(a, _) => a
    };
}

A payload pattern may itself be refutable — a literal or a range in a field is tested before the arm is taken. A payload written with field names may leave fields out, while a positional payload such as .Pair(a, _) lists every field. The shorthand needs a subject whose type is an enum or variant: on an int32, .Red is error: cannot infer enum or variant type for shorthand pattern '.Red' from type 'int32'. On a sum subject an unqualified case is refused; write its owner, as in Reading::Gauge { level }.

Typed patterns

A typed pattern, name: Type, fits a sum whose active member has that type, and binds the member, as that type, to the name. _: Type tests the member without binding it:

func Area(shape: Circle | Square) -> float64 {
    return match shape {
        c: Circle => 3.0 * c.radius * c.radius,
        s: Square => s.side * s.side
    };
}

The type after : is a complete type, so v: A | B needs no grouping. See Sum patterns for matching groups of members.

Absence and presence

On an optional, none fits the absent value and .Some(p) fits a present one whose value fits p. Each selects one level, so .Some(.Some(n)) reaches the value of an int32?? and .Some(none) matches a present absence:

func Describe(value: int32?) -> int32 {
    return match value {
        .Some(0) => -1,
        .Some(n) if n > 100 => 100,
        .Some(n) => n,
        none => 0
    };
}

A presence suffix is not a pattern: n?, n?? and none? are error: a presence suffix is not a pattern, with help: write '.Some(p)' to match a present value. Alternatives combine levels, as in none | .Some(0), and on an optional subject a typed pattern v: T selects one present level whose value has that type.

An error is not a value to match: the arms of a catch are patterns over the error itself — see Handling errors. Core's Result<T, E> is an ordinary variant, matched by its .Success(v) and .Failure(e) cases like any other.

Guards

pattern if condition fits when the pattern fits and the condition, a bool, is true. The condition is checked after the pattern, so it can read the pattern's bindings:

func Bucket(value: int32, small: bool) -> int32 {
    return match value {
        1..=9 if small => 1,
        1..=9 => 2,
        _ => 3
    };
}

A guard applies to the whole pattern before it, a range or a set of alternatives included. It is usually written at the end of an arm, but may also follow a pattern nested inside a tuple. A guard that is not a bool is error: pattern guard must have type 'bool', but found 'int32'. A guarded arm does not count towards exhaustiveness.

Alternatives

a | b fits a value that any of the alternatives fits, trying them in source order:

func Kind(c: char32) -> int32 {
    return match c {
        ' ' | '\t' | '\n' => 0,
        '0'..='9' => 1,
        _ => 2
    };
}

Alternatives may appear at any depth, as in .Digit(0 | 1), but they bind no names: error: pattern alternative cannot bind 'value'. A pattern that needs a binding gets an arm of its own. In a typed pattern the annotation is a whole type, so v: A | B is a sum annotation, not two alternatives.

See also