AnyCompiler

Functions

A Go function can return more than one value directly — no wrapping them in a tuple or object first. This is used constantly throughout Go's standard library, most famously for returning a result alongside an error.

package main

import "fmt"

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

func main() {
	quotient, remainder := divide(17, 5)
	fmt.Println(quotient, remainder)
}
Output
3 2

Multiple return values in practice

Because multiple return values are built into the language itself, a function like minMax below can return both the smallest and largest number from a slice in one call, and the caller just unpacks both with :=.

package main

import "fmt"

func minMax(numbers []int) (int, int) {
	min, max := numbers[0], numbers[0]
	for _, n := range numbers {
		if n < min {
			min = n
		}
		if n > max {
			max = n
		}
	}
	return min, max
}

func main() {
	low, high := minMax([]int{4, 8, 15, 16, 23, 42})
	fmt.Println(low, high)
}
Output
4 42

Next: control flow — if/else, and Go's single loop keyword.

Practice exercise

Write a function multiply(a, b int) int that returns a * b, then print multiply(6, 7).