Skip to content
Kavachकवच

Tuples

Also known as: tuple pair triple destructuring unpack multiple return values

● Beginner3 minBefore this: FunctionsSpec 2.3

A tuple groups a few values, of any types, in brackets: (200, "OK").

fn status() -> (Int, String) {
    (200, "OK")
}

fn main() {
    const pair = status()
    const (code, message) = pair
    print("{code} {message}")
}

The program ran and printed:

kavach run tuples.kav

200 OK
tuples.kav: Kavach code, then what running it prints

A tuple is handy for giving back two values from a function. Take it apart into names in one line:

fn min_max(xs: [Int]) -> (Int, Int) {
    (xs.min() ?? 0, xs.max() ?? 0)
}

fn main() {
    const (low, high) = min_max([4, 9, 2, 7])
    print("from {low} to {high}")
    print(min_max([5]))
}

The program ran and printed:

kavach run tuple-parts.kav

from 2 to 9(5, 5)
tuple-parts.kav: Kavach code, then what running it prints

Use tuples for short-lived groupings. When the same group is passed around, give its parts names with a record.