Docs · Language
Patterns
Vyi has one pattern grammar, used in five positions: match arms, if
bindings, shapeof tests, destructuring con declarations, and destructuring
parameters. This page lists the pattern forms, where each is accepted, and the
exhaustiveness, refutability, and narrowing rules built on them. It also states
the arm rules of switch, whose arms are values rather than patterns
(value arms). Guide
06, Pattern matching introduces them.
Where patterns appear
| Position | Form | Pattern must be |
|---|---|---|
match arm | Pattern: body, | any; the arms together must be exhaustive |
if binding | if Pattern = subject { ... } else { ... } | any; no match runs else, or nothing |
if binding with guard | if Pattern = subject; cond { ... } | any; binders are visible in cond |
shapeof | Pattern shapeof subject | no binders, only _; the test is a bool |
| destructuring declaration | con Pattern = expr | irrefutable (refutability) |
| destructuring parameter | fn f(Pattern: Type) | an irrefutable struct pattern |
Every position uses the grammar below. Restrictions that apply to one position are stated with the form.
A subject behind a pointer
A destructuring pattern looks through one pointer level, the way field access
does. When the subject is a pointer (*mut T, *con T, or *c_ptr T),
match p, if Pattern = p, Pattern shapeof p, and con Pattern = p
destructure the pointee *p. Arms, coverage, and refutability are those of
T, and each binder holds a copy of the value in its slot. A pointer to a
pointer needs an explicit * first. A whole-subject binder with no pattern
around it (if n = p) binds the pointer itself.
import { println } from "@fmt"
enum Shape { Circle(i32), Square(i32) }
struct Point { x: i32, y: i32 }
fn side(s: *con Shape) i32 {
return match s {
Circle(radius): radius * 2,
Square(side): side,
}
}
fn main() !u8 {
con square = Shape.Square(3)
println(side(&square)) // prints 3
mut origin = Point{ x: 1, y: 2 }
con p: *mut Point = &origin
con Point{ x, y } = p
println(y) // prints 2
return Ok(0)
}A switch compares its subject itself, so switch p over a pointer compares
the pointer. An arm of the pointee's type cannot be compared with it:
enum Color { Red, Green }
fn rank(p: *con Color) i32 {
return switch p {
Red: 1, // error: this `switch` arm has type Color
default: 0,
}
}The message ends by telling you to write switch *p.
The binder rule
A pattern is a shape with slots. A slot holds a name or _, optionally
followed by : Type:
| Slot | Meaning |
|---|---|
n | bind the value; its type is the slot's |
V | when V names a payload-less variant of the slot's type: match that variant, bind nothing |
_ | match anything, bind nothing |
n: T | bind, and require the value to be a T |
_: T | require a T without binding |
In n: T and _: T, T is the slot's type, a member of the slot's union, a
variant of the slot's enum, or a type pattern. Any other T
is a compile error.
A bare name is a variant exactly when the slot's type is an enum with a
payload-less variant of that name, or a union with exactly one member enum that
declares one. Any other bare name binds. The rule is the same for every enum
(None is an ordinary variant of Optional) and in every position: match
arm heads, if bindings, shapeof, payload slots, struct fields, and tuple
elements. Ok(None) matches an Ok holding None, and Some(Red) over a
?Color matches a Some holding Red.
import { println } from "@fmt"
enum Light { Red, Green }
fn canGo(light: ?Light) bool {
return match light {
Some(Green): true,
Some(Red): false,
None: false,
}
}
fn main() !u8 {
println(canGo(Some(Green))) // prints true
println(canGo(None)) // prints false
return Ok(0)
}A typed binder checks the slot's type and binds:
import { println } from "@fmt"
enum Token { Number(i32), Pair(i32, i32), End }
fn first(t: Token) i32 {
return match t {
Number(n): n,
Pair(a: i32, _): a,
End: 0,
}
}
fn main() !u8 {
println(first(Pair(4, 9))) // prints 4
return Ok(0)
}Every name a pattern binds is a con binding. There is no mut
destructuring:
struct Point { x: i32, y: i32 }
fn main() !u8 {
con p = Point{ x: 1, y: 2 }
mut Point(x, y) = p // error: destructuring binds immutably
return Ok(0)
}Variant names shared by members of a union
When more than one member enum of a slot's union declares a payload-less
variant of a name, the bare name is ambiguous and is a compile error that names
the candidates. The order of the union's members never decides. The same holds
at the head of an arm or an if binding whose subject is a union, and for a
bare variant in an expression
(enum construction).
enum Light { Off, Red }
enum Fan { Off, Low }
fn isOff(x: ?(Light | Fan)) bool {
return match x {
Some(Off): true, // error: `Off` is a variant of more than one member
default: false,
}
}Name the enum in an annotation, _: Fan.Off, or narrow the slot to one member
with n: Fan and match inside the arm:
import { println } from "@fmt"
enum Light { Off, Red }
enum Fan { Off, Low }
fn describe(x: ?(Light | Fan)) [*con]u8 {
return match x {
Some(_: Fan.Off): "fan off",
Some(_: Light.Off): "light off",
Some(Red): "red light",
default: "other",
}
}
fn main() !u8 {
println(describe(Some(Fan.Off))) // prints fan off
println(describe(Some(Red))) // prints red light
return Ok(0)
}Red is bare above because only Light declares it.
Arms over a union of enums
At the head of an arm over a union of enums, a variant matches when the union holds that member and the member is that variant. Write it bare when one member enum declares it, and with its enum otherwise. Its payload slots bind as they do over the enum itself. An arm naming one enum's variant never matches a value of another enum, even at the same position in its declaration:
import { println } from "@fmt"
enum Light { Off, On }
enum Fan { Off, Low }
fn describe(device: Light | Fan) [*con]u8 {
return match device {
Light.Off: "light off",
On: "light on",
Fan.Off: "fan off",
Low: "fan low",
}
}
fn main() !u8 {
println(describe(Fan.Off)) // prints fan off
println(describe(On)) // prints light on
return Ok(0)
}An arm naming a variant of an enum the subject can never hold is an error. In a generic body an arm that matches for some instantiation is accepted.
enum Light { Off, On }
enum Fan { Off, Low }
fn isOff(l: Light) bool {
return match l {
Fan.Off: true, // error: this `match` arm names a variant of Fan
default: false,
}
}Pattern forms
| Form | Example | Accepted in |
|---|---|---|
| wildcard binder | _, _: T | any slot |
| name binder | n, n: T | any slot; the top level of an if binding |
| literal | 1, 'a', "go", true | payload slots, struct fields, tuple elements (an equality test) |
| variant | Dot, Circle(r), Shape.Circle(r) | match arms, if bindings, shapeof, declarations, payload slots |
| struct | Point{ x }, Point{ x: a }, Point(a, b) | match arms, if bindings, declarations, parameters, payload slots, match typeof arms |
| tuple | (l, r) | match arms, declarations, payload slots |
| type | i32, Optional(i32), *_, ~Point | match typeof arms, binder types (type patterns) |
| error tag | FileGone, ParseError.Eof | arms of a match over an error value (error model) |
| catch-all | default | match and switch arms |
A match arm's head is decided at compile time: a variant, a type, an error
tag, or a pattern built from them, never a run-time value. A subject with no
shape to select on, such as an integer or a string, is rejected with
` match selects by shape ; choose by value with switch`.
Value arms: switch
A switch arm is not a pattern. It is an expression of the subject's type (a
literal, a binding, a field, a call) compared with the subject at run time. The
subject is evaluated once. Arms are tried top to bottom, and an arm's
expression is evaluated only when every arm above it failed.
| Arm | Matches when |
|---|---|
an expression e | subject == e; the subject's type needs ==, and a struct needs @eq |
a range lo..hi, lo...hi, ..hi, lo.. over a number or char subject | the subject lies in the range; .. excludes hi, ... includes it, an omitted end is unbounded |
a, b | any alternative matches, tried left to right |
default | no other arm matched; at most one, and it is the last arm |
import { println } from "@fmt"
fn kind(c: char, separator: char) [*con]u8 {
return switch c {
' ': "space",
separator: "separator",
'0'...'9': "digit",
default: "other",
}
}
fn main() !u8 {
println(kind(',', ',')) // prints separator
println(kind('7', ',')) // prints digit
return Ok(0)
}A range arm is a containment test because of its type, not its spelling: a
range held in a binding is a containment test too, and its bounds may be
run-time values. Over an enum subject a variant is an ordinary value, written
bare (Red:) or with its enum (Color.Red:).
A destructuring arm is not a value, so a switch rejects it:
enum Shape { Dot, Circle(i32) }
fn radius(s: Shape) i32 {
return switch s {
Circle(r): r, // error: a `switch` arm is a value
default: 0,
}
}A chain of conditions is a switch over true (guide
05, guard chains):
import { println } from "@fmt"
fn grade(score: i32) [*con]u8 {
return switch true {
score >= 90: "A",
score >= 80: "B",
default: "C",
}
}
fn main() !u8 {
println(grade(85)) // prints B
return Ok(0)
}Variant patterns
A variant in a match arm is written bare; the subject's type resolves it.
Parentheses destructure the payload. A payload-less variant is written bare in
every position (empty parentheses, Dot(), are accepted and mean the same).
import { println } from "@fmt"
enum Shape { Dot, Circle(i32), Rect(i32, i32) }
fn describe(s: Shape) [*con]u8 {
return match s {
Dot: "a dot",
Circle(0): "an empty circle",
Circle(r): "a circle",
Rect(w, h): "a rectangle",
}
}
fn main() !u8 {
println(describe(Circle(0))) // prints an empty circle
println(describe(Circle(5))) // prints a circle
return Ok(0)
}A literal in a payload slot is an equality test on that position. An arm with one covers only part of its variant, so it goes above the arm that takes the rest.
Any variant pattern may be written with its enum, Shape.Dot or
Shape.Circle(r), at the head of an arm, in an if binding, or nested in a
slot. The qualified form selects the same variant and counts the same for
exhaustiveness. It is how you tell apart a name that several enums of a union
declare. The qualifier names the subject's enum or a member enum of its union;
any other enum is an error.
In an if binding, a payload-less variant of the subject's type is that
variant:
import { println } from "@fmt"
enum Color { Red, Green, Blue }
fn isGreen(c: Color) bool {
return if Green = c { true } else { false }
}
fn main() !u8 {
println(isGreen(Green)) // prints true
println(isGreen(Red)) // prints false
return Ok(0)
}Patterns nest to any depth. A payload slot holds another variant pattern, a struct pattern, a tuple pattern, or a literal:
import { println } from "@fmt"
struct Point { x: i32, y: i32 }
enum Place { At(Point), Nowhere }
fn column(p: ?Place) i32 {
return match p {
Some(At(Point{ x })): x,
Some(Nowhere): -1,
None: -1,
}
}
fn main() !u8 {
println(column(Some(At(Point{ x: 4, y: 7 })))) // prints 4
return Ok(0)
}Binder narrowing to a payload's variant
When a payload is an enum, a binder's : Type may name one of that enum's
variants. The arm then matches only when the payload is that variant.
_: Interrupted checks without binding, e: Closed checks and binds, and
e: _ takes what is left. For a payload-less variant the bare name,
Err(Interrupted), says the same as Err(_: Interrupted).
import { println } from "@fmt"
enum ReadError { Interrupted, Closed, Frozen }
fn describe(r: ReadError!i32) [*con]u8 {
return match r {
Ok(_): "ok",
Err(_: Interrupted): "try again",
Err(e: Closed): "closed",
Err(e: _): "failed",
}
}
fn main() !u8 {
println(describe(Err(Interrupted))) // prints try again
println(describe(Err(Frozen))) // prints failed
return Ok(0)
}A variant-narrowed arm covers only that slice of its variant. Arms that
together name every inner variant cover the whole variant, with no e: _ arm.
When some are left out, the match is rejected and the message names them:
enum ReadError { Interrupted, Closed }
fn describe(r: ReadError!i32) [*con]u8 {
return match r { // error: non-exhaustive match; missing Err(Closed)
Ok(_): "ok",
Err(_: Interrupted): "try again",
}
}The variant may be written with its enum, _: ReadError.Closed; the enum must
be the slot's. When the payload is a union, the variant names the one member
enum that declares it. The arm matches when the union holds that member and the
member is that variant, and a binder takes the member's value. A variant that
two member enums declare is written with its enum.
An annotation that names neither a type the slot can be narrowed to nor a variant of its enum is an error, never a match of every value:
enum Light { Off, Red }
enum Fan { Off, Low }
fn isLow(x: ?Light) bool {
return match x {
Some(_: Fan.Low): true, // error: this pattern slot holds Light
default: false,
}
}Binder narrowing to a union's member
When a payload is a union, a binder's : Type may name one of its member
types. The arm matches only when the union holds that member, and the binder is
the member value. The error slot of a function with an inferred error set
(guide 07) is the common case:
import { println } from "@fmt"
enum SaveError { DiskFull }
enum NetError { Timeout }
fn save(ok: bool) SaveError!() {
if !ok { return Err(DiskFull) }
return Ok(())
}
fn send(ok: bool) NetError!() {
if !ok { return Err(Timeout) }
return Ok(())
}
fn sync(saved: bool, sent: bool) ! {
try save(saved)
try send(sent)
return Ok(())
}
fn report(saved: bool, sent: bool) [*con]u8 {
return match sync(saved, sent) {
Ok(_): "synced",
Err(e: SaveError): "save failed",
Err(e: NetError): "send failed",
}
}
fn main() !u8 {
println(report(true, false)) // prints send failed
return Ok(0)
}sync's error set is SaveError | NetError, and the two member-narrowed arms
cover all of it, so the match needs no catch-all. Cover only some members and
the match is rejected, naming the missing slice (missing Err(NetError)). An
Err(_) arm takes the rest when you don't need each member apart.
Struct patterns
A struct pattern takes fields by name, renames them with field: name, or
takes them by position in declaration order with parentheses. Fields left out
are not bound. Naming a field the struct doesn't have is an error.
import { println } from "@fmt"
struct Point { x: i32, y: i32 }
fn main() !u8 {
con p = Point{ x: 3, y: 8 }
con Point{ x, y } = p // by name
con Point{ x: left } = p // renamed; y is not bound
con Point(_, top) = p // by position
println(left) // prints 3
println(top) // prints 8
return Ok(0)
}A struct value has one shape, so in a match one arm that binds its fields
covers it. A literal or a nested pattern in a field slot makes the arm match
only some values. Arms are tried top to bottom, and arms that all test a
literal need one more arm that takes every value, or default:
import { println } from "@fmt"
struct Point { x: i32, y: i32 }
fn place(p: Point) [*con]u8 {
return match p {
Point{ x: 0, y: 0 }: "origin",
Point{ x: 0, y }: "on the y axis",
Point{ x, y: 0 }: "on the x axis",
Point{ x, y }: "elsewhere",
}
}
fn main() !u8 {
println(place(Point{ x: 0, y: 5 })) // prints on the y axis
return Ok(0)
}As a parameter, the pattern sits where the name would be:
import { println } from "@fmt"
struct Size { width: i32, height: i32 }
fn area(Size(width, height): Size) i32 {
return width * height
}
fn main() !u8 {
println(area(Size{ width: 2, height: 5 })) // prints 10
return Ok(0)
}Tuple patterns
A tuple pattern takes elements by position, in a declaration or a match arm.
In an arm, a literal in a slot tests that element, and patterns nest.
import { println } from "@fmt"
fn describe(order: (i32, bool)) [*con]u8 {
return match order {
(0, _): "empty",
(count, true): "express",
(count, _): "standard",
}
}
fn main() !u8 {
con (count, express) = (3, true)
println(count) // prints 3
println(describe((count, express))) // prints express
return Ok(0)
}Under match typeof, where every arm is a type, (i32, bool) is the tuple
type.
match typeof: selecting a union's member
A union value (i32 | Size) holds one of its member types and records which.
match typeof u chooses an arm by that member. An arm names a type, or gives a
struct pattern that destructures the member. A type arm is an ordinary type
expression: a generic call such as Optional(i32) works, and a name bound to a
type (type Id = i32) is the type it names. Inside a type arm, u has the
matched type.
import { println } from "@fmt"
struct Size { width: i32, height: i32 }
fn area(u: i32 | Size) i32 {
match typeof u {
Size{ width, height }: return width * height,
i32: return u * u,
}
}
fn main() !u8 {
println(area(Size{ width: 2, height: 3 })) // prints 6
println(area(4)) // prints 16
return Ok(0)
}The typeof is required. A union's cases are its member types:
fn describe(u: i32 | bool) [*con]u8 {
return match u { // error: a union value's members are selected through its type
i32: "number",
bool: "flag",
}
}A singleton union (1 | "go") is selected the same way, each arm naming one
member value. It is also a switch subject, whose arms compare with ==
(types, structural unions). Either form covers it
when every member has an arm:
import { println } from "@fmt"
fn speed(mode: "fast" | "slow") i32 {
match typeof mode {
"fast": return 2,
"slow": return 1,
}
}
fn label(mode: "fast" | "slow") [*con]u8 {
return switch mode {
"fast": "hurry",
"slow": "stroll",
}
}
fn main() !u8 {
println(speed("slow")) // prints 1
println(label("fast")) // prints hurry
return Ok(0)
}The if form is a top-level binder with a type: if n: i32 = u matches when
u holds an i32 and binds it (if bindings).
Type patterns
Where a type is matched rather than declared, it may be a type pattern: a type with holes and looser pointer forms.
| Pattern | Matches |
|---|---|
_ | any type |
Point | exactly Point |
*mut Point, *con Point | exactly that pointer |
*Point | a pointer to Point, of either mutability |
~Point | a Point, or a pointer to one of either mutability |
Box(_), *_, ~Box(_), (i32, _) | the same forms with holes, at any depth |
Type patterns are written in four places: the arms of match typeof, the type
of a binder in a match arm, an if binding, or a shapeof test, the
receiver of a method import item
(methods and dispatch), and the
receiver of an interface method
(interfaces). An anonymous interface writes
its receiver with _, as fn (s: ~_) area() i32. A function type is an arm
like any other type. In a generic body the arm is chosen per instantiation: the
first that matches.
import { println } from "@fmt"
struct Point { x: i32, y: i32 }
fn describe(value: _) [*con]u8 {
return match typeof value {
*mut Point: "a mutable Point pointer",
*_: "some other pointer",
~Point: "a Point",
fn(i32) i32: "a function",
default: "something else",
}
}
fn double(n: i32) i32 { return n * 2 }
fn main() !u8 {
mut origin = Point{ x: 0, y: 0 }
con count = 3
println(describe(&origin)) // prints a mutable Point pointer
println(describe(&count)) // prints some other pointer
println(describe(origin)) // prints a Point
println(describe(double)) // prints a function
return Ok(0)
}Over a union, a type pattern arm selects every member it matches. When it
matches one, the subject has that member's type inside the arm; when it matches
several, the subject keeps the union's type, as in an arm with several heads. A
binder whose type is a pattern binds the subject as it is: s: ~Shape takes a
Shape or a pointer to one without dereferencing it, and p: *_ over a union
takes the pointer members.
import { println } from "@fmt"
struct Point { x: i32, y: i32 }
fn firstX(o: ?(i32 | *mut Point)) i32 {
return match o {
Some(p: *_): p.x, // p is the *mut Point
Some(n: i32): n,
None: 0,
}
}
fn main() !u8 {
mut corner = Point{ x: 7, y: 1 }
println(firstX(Some(&corner))) // prints 7
return Ok(0)
}Anywhere else a type pattern is an error: a real type states its pointer's mutability and names exactly one type.
struct Point { x: i32, y: i32 }
fn norm(p: ~Point) i32 { // error: `~T` is a type pattern
return 0
}An arm or binder that can never match is an error that says why:
struct Point { x: i32, y: i32 }
fn isConst(u: i32 | *mut Point) bool {
match typeof u {
*con _: return true, // error: this arm never matches
default: return false,
}
}Multi-pattern arms
Patterns separated by commas before the : are alternatives sharing one body:
import { println } from "@fmt"
enum Color { Red, Orange, Blue }
fn isWarm(c: Color) bool {
return match c {
Red, Orange: true,
Blue: false,
}
}
fn main() !u8 {
println(isWarm(Orange)) // prints true
return Ok(0)
}In a match, alternatives bind nothing: a binder would have no value when
another alternative matched. Payload slots in alternatives are _.
enum ParseError { Empty }
fn classify(r: ParseError!i32) i32 {
return match r {
Ok(n), Err(_): 1, // error: a multi-pattern arm matches without binding
}
}The default catch-all
The catch-all arm is default in both match and switch. It matches when no
other arm did and satisfies exhaustiveness. An arm list has at most one, and it
is the last arm.
_ is not an arm. At the head of an arm the compiler reads it as a type to
infer from the surrounding code, which fails:
enum Color { Red, Green, Blue }
fn hue(c: Color) i32 {
return match c {
Red: 1,
_: 0, // error: cannot infer match arm type from the surrounding code
}
}default is a contextual word, not a reserved one. Only an arm that is exactly
the bare word is the catch-all. A variant, binding, or type named default is
written in parentheses:
import { println } from "@fmt"
enum Mode { default, fast, safe }
fn describe(m: Mode) [*con]u8 {
return match m {
(default): "the default mode",
fast: "fast",
default: "another mode",
}
}
fn main() !u8 {
println(describe(Mode.default)) // prints the default mode
println(describe(safe)) // prints another mode
return Ok(0)
}Exhaustiveness
A match accounts for every shape its subject can have, or has a default
arm:
match subject | Rule |
|---|---|
| enum | every variant needs an arm. An arm with a literal slot (Some(0)), a narrowed binder (Err(_: Interrupted), Err(e: SaveError)), or a nested pattern (Ok(Some(v))) covers only what it names, at any depth. Arms that together select every inner variant, union member, or value cover the variant; what is left is reported by name (Ok(None), Ok(Some(None))) |
| struct or tuple | one shape: an arm whose every slot is a binder or _ covers it. Arms that test a literal or a nested pattern in a slot are partial, and count as they do in a payload |
typeof a union | every member type needs an arm |
typeof a singleton union (1 | "go", 'a' | 'b') | every member value needs an arm |
error | the set is open, so no list of tags is complete: a default arm is required |
A missing case is reported by name, on the line of the match:
enum Color { Red, Green, Blue }
fn hue(c: Color) i32 {
return match c { // error: non-exhaustive match; missing Blue
Red: 1,
Green: 2,
}
}Coverage looks through every layer of nesting, so a missing case is named as deep as it lies:
fn depth(r: i32!??i32) i32 {
return match r { // error: non-exhaustive match; missing Ok(Some(None))
Ok(Some(Some(v))): v,
Ok(None): 0,
Err(_): -1,
}
}An arm whose every value the arms above it already select can never match, and
is an error at any depth. The default arm is exempt. In a generic function
which arms can match depends on the instantiation, so none is reported there.
enum Cart { Empty, Items(i32) }
fn summary(c: Cart) [*con]u8 {
return match c {
Empty: "empty",
Items(_): "several items",
Items(1): "one item", // error: this arm can never match
}
}switch coverage
A switch has a default arm or an arm for every case, as a statement and as
an expression. Coverage is proved only from known arms: an arm whose value or
range bounds are not known values covers nothing for this
purpose.
switch subject | Covered without default by |
|---|---|
bool | true and false |
| enum with no payloads | every variant |
singleton union (1 | 2, "fast" | "slow", 1 | "go") | every member |
integer or char | known values and ranges that together span the whole type (..0, 0, 1..) |
anything else (strings, floats, structs, type, a union with a member that is not a single value) | nothing: default is required |
import { println } from "@fmt"
fn sign(n: i32) i32 {
return switch n {
..0: -1,
0: 0,
1..: 1,
}
}
fn main() !u8 {
println(sign(-8)) // prints -1
return Ok(0)
}An uncovered switch is rejected. The error names what is missing when the
subject's cases can be listed, and otherwise says that the subject's type needs
a default:
fn label(n: i32) [*con]u8 {
return switch n { // error: a `switch` without `default` must cover every case; missing ...0, 3..
1: "one",
2: "two",
}
}A dispatch that does not cover its subject is one error: label is not also
reported as failing to return a value. In a generic function coverage is
checked for each instantiation.
Known arms also reject an arm that the arms above it already cover completely: a repeated value, or a value or range inside earlier ranges. Partial overlap is allowed, and the first arm that matches wins.
fn band(n: i32) i32 {
return switch n {
1..10: 1,
5: 2, // error: this arm can never match
default: 0,
}
}Refutability of destructuring declarations
A destructuring declaration or parameter has no else, so its pattern must be
irrefutable (certain to match) at every depth:
- A binder or
_matches anything. - A struct or tuple pattern is irrefutable when every field or element pattern is.
- A variant pattern is irrefutable when its variant is the only one the value can hold (the enum has one variant, or narrowing leaves one) and its payload patterns are irrefutable. A bare payload-less variant in a slot (
None) is a variant pattern. - A literal in a slot matches one value, so it is refutable.
- Multi-pattern alternatives are not declaration forms.
The error points at each part that can fail, however deep: `con (a, Some(x)) =
t is rejected at Some(x)`.
import { println } from "@fmt"
enum Celsius { Degrees(i32) }
fn main() !u8 {
con reading = Celsius.Degrees(21)
con Degrees(value) = reading
println(value) // prints 21
return Ok(0)
}A pattern is judged by what the binding can hold at that point, not only by its declared type. Over an enum with several variants, a variant pattern can fail unless a test, an initializer, or an assignment has ruled the other variants out. Then it cannot, and the declaration reads the payload directly:
import { println } from "@fmt"
fn orZero(o: ?i32) i32 {
if o == None { return 0 }
con Some(n) = o // o holds Some here
return n
}
fn main() !u8 {
println(orZero(Some(4))) // prints 4
return Ok(0)
}The same holds for any enum, for a union narrowed to one member, and for nested patterns, whose inner slots are still judged by their own types. Only a binding narrows; a field path or a call result is judged by its type. Where the pattern can still fail, the error says what the binding may still hold and how to rule it out:
fn first(o: ?i32) i32 {
con Some(n) = o // error: `o` may still be `None` here
return n
}Binders at the top level of if
if Pattern = subject accepts every form above, plus a top-level binder with a
: Type. Over a union it tests the member; over a singleton union it tests the
value.
import { println } from "@fmt"
fn describe(u: i32 | bool) [*con]u8 {
if n: i32 = u { return "a number" }
return "a flag"
}
fn isSlow(mode: "fast" | "slow") bool {
if m: "slow" = mode { return true }
return false
}
fn main() !u8 {
println(describe(7)) // prints a number
println(isSlow("slow")) // prints true
return Ok(0)
}A ; guard after the subject adds a condition evaluated with the binders in
scope. The branch runs when the pattern matches and the guard holds.
import { println } from "@fmt"
fn bigEnough(o: ?i32) bool {
if Some(n) = o; n >= 10 { return true }
return false
}
fn main() !u8 {
println(bigEnough(Some(12))) // prints true
println(bigEnough(Some(3))) // prints false
return Ok(0)
}A binder that can never match is an error that says why and what to write.
Over a subject that is not a union, n: T names the subject as it is, so a T
the subject never is never matches, including the pointee of a pointer subject.
A binder in a payload slot is held to the same rule. In a generic body a binder
that matches for some instantiation is accepted.
enum Shape { Circle(i32), Square(i32) }
fn isShape(p: *con Shape) bool {
if s: Shape = p { return true } // error: the subject is `*con Shape`, not `Shape`
return false
}Narrowing
A binding declared with a union or an enum type can be known to hold only some of its members at a point in a function: some member types of a union, some variants of an enum, or both for a union of enums. Within one function body, what is known at a point types every read of the binding there. Its storage is always its declared type; narrowing changes how a read is typed, never the layout.
What narrows
- Tests. A
match typeofarm, anif n: T = vbinding, andtypeof v == Tortypeof v != Tselect member types. Amatcharm, anifbinding (if None = o,if Some(x) = o), and==or!=with a payload-less variant (o == None,s != Shape.Dot) select variants.==or!=with a literal selects members of a singleton union. Inside the branch where the test holds, the binding keeps what the test selects. In the branch where it fails, it loses what the test takes entirely (an arm orifbinding whose payload slots are all binders or_). After anifwhose branch ends inreturn,break,continue, orpanic, the code that follows has the other branch's knowledge. - Initializers.
con a: i32 | bool = 7andmut v: i32 | bool = 7hold ani32until something changes them;mut o: ?i32 = NoneholdsNone. - Assignments.
v = xgives amutwhatxis.
An unannotated binding takes the type its initializer has at that point, narrowing included. Write the type to keep it wide.
Comparing a binding with a value it cannot equal at that point is an error: after
con u: i32 | bool = 1, u == true is always false, and the compiler says so,
pointing at where u was narrowed.
Only the built-in comparison of variants narrows. An == that the type
overrides with @eq means what the method says and narrows nothing.
What narrowing gives
A read of a binding known to hold one member type has that type, so v + 1
compiles. Known to hold several members of a union, it keeps the union's type,
and so does every read of an enum. What it may hold is then a coverage fact: a
later match or switch needs arms only for the rest, and an if binding
whose pattern takes everything it may still hold always matches. An arm or
branch that narrowing rules out is not an error (an arm is an error only when
no value of the declared type can match it); its body is typed as if its test
held on the declared type.
import { println } from "@fmt"
enum Shape { Dot, Circle(i32), Square(i32) }
fn area(s: Shape) i32 {
if s == Dot { return 0 }
return match s { // Dot is ruled out: no arm needed
Circle(r): 3 * r * r,
Square(w): w * w,
}
}
fn main() !u8 {
mut reading: i32 | bool = 7
println(reading + 1) // prints 8
println(area(Square(3))) // prints 9
return Ok(0)
}Where narrowing ends
For a mut:
- An assignment replaces what it holds.
- Where paths that left it different join (after an
if,match, orswitch, and at the head of a loop whose body may change it), it holds the union of what each path holds. A loop's head takes what every pass back to it can hold. - Taking its address ends the knowledge for good.
&vhas the declared type, the pointer may write any member, and from then on, including later passes of an enclosing loop, reads have the declared type and assignments do not narrow it.
fn pick(useNumber: bool) i32 {
mut v: i32 | bool = 1
if useNumber { v = 2 } else { v = true }
con n: i32 = v // error: this value has type i32 | bool, but the binding is declared i32
return n
}A con's address is a *con pointer, so taking it ends nothing.
Calls, closures, and file-level variables
Knowledge never crosses a call: a parameter starts every body at its declared
type. A narrowed value is accepted wherever a value it fits is expected: a
parameter of its declared union, of a wider union, or of its member. A closure
captures by value what a name means where the closure is written (a mut
cannot be captured).
A file-level mut narrows within a body only until code outside the body may
run: every call, and every operator, index, struct literal, try, catch, and
non-range for ... in, since each may call a method. Its initializer does not
narrow it, and one whose address is taken anywhere is never narrowed.
Methods on a narrowed binding
A method called on a binding narrowed to a member gets what its receiver type
asks for: a pointer receiver of the member gets the address of the member
inside the binding's storage, and a value receiver gets a copy. On a narrowed
mut, calling a pointer-receiver method that keeps or returns something tied to
its receiver is an error, because an assignment could put another member where
the kept pointer points. Copy the value out first, or declare the binding
con.
struct Counter { count: i32 }
fn (c: *mut Counter) itself() *mut Counter { return c }
fn main() !u8 {
mut slot: i32 | Counter = Counter{ count: 1 }
con p = slot.itself() // error: `itself` keeps or returns its receiver
return Ok(0)
}Singleton unions
Singleton unions narrow by value, and the refinements chain:
import { println } from "@fmt"
fn onlyThree(n: 3) [*con]u8 { return "three" }
fn name(n: 1 | 2 | 3) [*con]u8 {
if n == 1 { return "one" }
if m: 2 = n { return "two" }
return onlyThree(n) // n is 3 here
}
fn main() !u8 {
println(name(3)) // prints three
return Ok(0)
}After n == 1 returns, n is 2 | 3; after the if binding on 2 returns,
it is 3, which onlyThree accepts.
See also: guide 06, Pattern matching,
guide 05, Control flow for switch and
match arms, and statements for declarations.