Slide 13 of 37
Pattern matching with is
Variant patterns
type Shape {
Circle { radius: Int }
Rectangle { width: Int, height: Int }
}
proc main(): void {
shape := Shape.Circle(4)
if shape is Shape.Circle(r) { echo "circle, r={r}" }
else if shape is Shape.Rectangle(w, _) { echo "rect, w={w}" }
}
Vector patterns
proc main(): void {
command := ["move", "north", "2"]
if command is ["move", dir, ...steps] { echo "{dir}, {len(steps)} more" }
else if command is ["stop"] { echo "halt" }
}
String patterns
proc main(): void {
path := "/users/42/posts/7"
if path is "/users/{id}/posts/{postId}" { echo "{id} / {postId}" }
}
`is` checks a value against a pattern and yields a Bool, narrowing it and binding names usable right away — in the rest of the condition after &&, and in the branch body. There is no match statement; every match is an ordinary if/else if chain. Four kinds of pattern exist: a variant, a Result, a vector matched positionally with an optional ...rest, and a string template whose {holes} bind the text between literal pieces.