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) + 5What’s worth noticing:
Point { x, y: other }: struct destructuring.xbinds thexfield to a local of the same name;y: otherbinds theyfield to a local namedother.case None => 0: matching theNonevariant of aT | Noneoptional.case NetworkError { code }in aPoint | NetworkErrorunion: patterns can pick out arms of an ad-hoc union.case Some(Point { x }): nested destructuring.Somecarries aPointpayload;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.