/ Pattern Matching
Documentation

Getting Started

Language Guide

SDL2 and Graphics

CLI Reference

Pattern Matching

The match statement branches on a value by comparing it against a series of patterns. It is more powerful than a chain of if/elif because it can destructure struct types and bind their fields to variables.

Basic Match

The simplest form matches a value against literal or enum patterns.

let code: int = 2

match code:
    case 1:
        print("one")
    case 2:
        print("two")
    case 3:
        print("three")
    default:
        print("other")

Type Pattern Matching

Type patterns check whether the matched value is an instance of a particular struct type and simultaneously bind its fields to local variables. This enables polymorphic dispatch without virtual functions.

The syntax is TypeName(field1, field2, ...) where the names are new local variables bound to the struct's fields in declaration order.

struct Circle:
    radius: float

struct Rectangle:
    width: float
    height: float

fn area(shape: Shape) -> float:
    match shape:
        case Circle(r):
            # r is bound to shape.radius
            return 3.14159 * r * r
        case Rectangle(w, h):
            # w is width, h is height
            return w * h
        default:
            return 0.0

The bound variables exist only within that case block. They are not accessible in other cases or after the match statement.

Multiple Patterns per Case

A single case can match multiple values by separating them with commas.

match day:
    case "Saturday", "Sunday":
        print("weekend")
    default:
        print("weekday")
← Enums Interfaces →