Skip to content

Pattern matching

match as a statement and as an expression; supported pattern forms.

match works as both a statement and an expression. Each case has a pattern; the first matching arm runs.

Expression arms use case Pattern => expr and currently appear in let, assignment, and return positions:

let value: i32 = match result:
case Ok(x) => x
case Err(e):
print_i32(0)
yield 42

Block-form arms use case Pattern: and must end with yield expr.

Statement matches use block arms and may include an else::

match optional:
case Point { x, y: yy }:
print_i32(x + yy)
case None:
return None
  • None
  • Type: matches when the scrutinee is exactly that type
  • Type as name: binds the typed view to a name
  • Struct { field }: destructures a single field
  • Struct { field: binding }: destructures with a rename
  • Variant: matches a payloadless enum case
  • Variant(binding): captures the named payload
  • Variant(Struct { field }): nested destructuring

Guard clauses (case Ok(x) if x > 0) are reserved but not yet supported.

struct Point:
x: i32
y: i32
enum MaybePoint:
case Some(value: Point)
case Empty
def from_optional(point: Point | None) -> i32:
return match point:
case Point { x, y: other } => x + other
case None => 0
def from_enum(value: MaybePoint) -> i32:
return match value:
case Some(Point { x }) => x
case Empty => 0

See examples/pattern-matching for the full file this snippet was lifted from.