Skip to content
Kavachकवच

Match: Patterns

● Beginner4 min

Patterns can be ranges, tuples, union variants, none, or _ for anything.

fn main() {
    const score = 72
    print(match score {
        90..=100 => "A"
        75..=89 => "B"
        0..=74 => "C"
        _ => "not a score"
    })
    const point = (0, 5)
    print(match point {
        (0, 0) => "the origin"
        (0, y) => "on the y axis, at {y}"
        _ => "somewhere else"
    })
}

The program ran and printed:

kavach run patterns.kav

Con the y axis, at 5
patterns.kav: Kavach code, then what running it prints
  • 90..=100 matches any number in the range.
  • (0, y) matches a pair whose first item is 0, and names the second y.
  • A union variant matches its own case: records and unions show it.