Multiple Return Values

Functions in Tengo can return more than one value using a comma-separated return list. The caller unpacks them with a multi-assignment.

fmt := import("fmt")
minmax := func(arr) {
    mn := arr[0]
    mx := arr[0]
    for _, v in arr {
        if v < mn { mn = v }
        if v > mx { mx = v }
    }
    return mn, mx
}
lo, hi := minmax([3, 1, 4, 1, 5, 9, 2, 6])
fmt.println("min: ", lo)
fmt.println("max: ", hi)
divide := func(a, b) {
    if b == 0 {
        return 0, error("division by zero")
    }
    return a / b, undefined
}

result, err := divide(10, 3)
fmt.println("result: ", result)

_, err = divide(5, 0)
fmt.println("is_error: ", is_error(err))

try it

min: 1
max: 9
result: 3
is_error: true
loading…