Skip to content

Pattern matching

Match expressions over optional, union, and enum types with destructuring.

struct Point:
x: i32
y: i32
struct NetworkError:
code: 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_union(result: Point | NetworkError) -> i32:
return match result:
case Point { x } => x
case NetworkError { code } => code
def from_enum(value: MaybePoint) -> i32:
return match value:
case Some(Point { x }) => x
case Empty => 0
def main() -> i32:
let point: Point = Point(x=20, y=2)
let maybe: MaybePoint = Some(value=Point(x=10, y=0))
return from_optional(point) + from_union(NetworkError(code=5)) + from_enum(maybe) + 5

What’s worth noticing:

  • Point { x, y: other }: struct destructuring. x binds the x field to a local of the same name; y: other binds the y field to a local named other.
  • case None => 0: matching the None variant of a T | None optional.
  • case NetworkError { code } in a Point | NetworkError union: patterns can pick out arms of an ad-hoc union.
  • case Some(Point { x }): nested destructuring. Some carries a Point payload; Point { x } destructures that payload in-place.

This is the only file in the examples that mixes three different pattern shapes (optional, union, enum) so you can see how they read in context.

For the full pattern grammar, see Pattern matching.