Multiple return values

A Go function can return more than one value from a single call. That is unusual among mainstream languages (C, Java, and most others force you to wrap multiple outputs in an object or use out-parameters), and it changes the shape of Go code in important ways.

Two values at once

Put each return type in parentheses after the parameter list:

func divmod(a, b int) (int, int) {
    return a / b, a % b
}

divmod returns the quotient and the remainder of integer division in one call. The return statement lists the two values separated by a comma, in the same order as the types in the signature.

Callers receive both values with a parallel assignment, the same shape you used to declare multiple variables at once in the Variables lesson:

q, r := divmod(17, 5)

fmt.Println(q, r)   // 3 2

q gets the first return, r gets the second. You can use any names you like; the order of values is what matters, not the names.

The (result, error) idiom

The most common use of multiple returns in real Go code is error handling. Many functions that can fail return two values: the result you asked for, and an error describing what went wrong. The caller uses the short-statement if to check the error before touching the result.

The shape you will meet everywhere (the error type gets its own chapter later in the course):

result, err := someFunction(args)
if err != nil {
    // handle err and return / continue / whatever
}
// use result

Compared to exception-based languages, this keeps failures in the open. Instead of a hidden control-flow mechanism that jumps out of the function, failures are values the caller can inspect right away. It is verbose, but it makes the unhappy path visible at the call site.

The unused-variable rule still applies

If you only need some of the values, use the blank identifier _ for the rest, same as you did in range loops:

q, _ := divmod(17, 5)   // keep the quotient, discard the remainder
fmt.Println(q)           // 3

Trying to stuff two returns into one variable is a compile error:

q := divmod(17, 5)   // compile error: assignment mismatch: 1 variable but divmod returns 2 values

When you want only some of the returned values, _ makes the discard explicit. That matters most with the (result, error) pattern, where keeping the result and throwing away the error should be an obvious choice in the code, not something hidden by omission.

Task
  • Write a function called minMax that takes two int parameters.
  • Return two values in this order: the smaller number first, then the larger.
  • Keep the existing divmod call in main.
  • Call minMax(8, 3) from main and print both return values on one line with fmt.Println.
Expected output
3 2
3 8