Functions & Multiple Returns
Functions can return more than one value.
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, 2Implement add(a, b int) int and divmod(a, b int) (int, int) returning (quotient, remainder). A hidden test suite exercises them, including negative operands.
- TestAddBasicspending
- TestAddLargepending
- TestDivmodPositivepending
- TestDivmodZeroDividendpending
Hint
Integer division / gives the quotient, % gives the remainder. Return both from divmod on a single return line.
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.
- TestMinMaxTypicalpending
- TestMinMaxSinglepending
- TestMinMaxEmptypending
Hint
Seed both min and max with nums[0] (only after the empty check), then range through the rest updating each.