Skip to content
Kavachकवच

Match: Guards

● Beginner3 min

A guard, pattern if condition, adds a check to a pattern.

type Shape = Circle(radius: Float) | Rect(width: Int, height: Int)

fn describe(shape: Shape) -> String {
    match shape {
        Shape.Circle(radius) => "circle of radius {radius}"
        Shape.Rect(width, height) if width == height => "square of side {width}"
        Shape.Rect(width, height) => "{width} by {height} rectangle"
    }
}

fn main() {
    print(describe(Shape.Circle(radius: 2.0)))
    print(describe(Shape.Rect(width: 3, height: 3)))
    print(describe(Shape.Rect(width: 4, height: 2)))
}

The program ran and printed:

kavach run guards.kav

circle of radius 2.0square of side 34 by 2 rectangle
guards.kav: Kavach code, then what running it prints

The square case is a Rect whose sides are equal. The plain Rect arm after it catches the rest, so every shape is still covered.