Path/Stage 1 · Foundations

Functions & Multiple Returns

Functions can return more than one value.

Gopher narrator

Have the gopher read this explanation out loud.

Parameters that share a type can be grouped: func f(a, b int). A function may return several values, commonly a result plus an error.

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

q, r := divmod(17, 5) // 3, 2
Exercise 1·code

Implement add(a, b int) int and divmod(a, b int) (int, int) returning (quotient, remainder). A hidden test suite exercises them, including negative operands.

Plate · main.go
Loading...
Test suite · go test
  • TestAddBasicspending
  • TestAddLargepending
  • TestDivmodPositivepending
  • TestDivmodZeroDividendpending
Hint

Integer division / gives the quotient, % gives the remainder. Return both from divmod on a single return line.

Exercise 2·code

Implement minMax(nums []int) (min, max int, ok bool) using named return values. When nums is empty, return (0, 0, false); otherwise return the smallest, largest, and true.

Plate · main.go
Loading...
Test suite · go test
  • TestMinMaxTypicalpending
  • TestMinMaxSinglepending
  • TestMinMaxEmptypending
Hint

Seed both min and max with nums[0] (only after the empty check), then range through the rest updating each.