๐ŸŽ“ A1Learner
๐Ÿ”

Go Multiple Returns

A Go function can send back more than one result at once. A function that returns two values lists both result types in parentheses.

Quotient and remainder together

The divide function returns the quotient and the remainder. One call fills both variables.

package main

import "fmt"

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

func main() {
	q, r := divide(17, 5)
	fmt.Println(q)
	fmt.Println(r)
}

A search returns a position and a bool

The findName function returns the index of the match. It also returns a bool that says whether a match was found.

package main

import "fmt"

func findName(names []string, target string) (int, bool) {
	for i, name := range names {
		if name == target {
			return i, true
		}
	}
	return -1, false
}

func main() {
	names := []string{"Ana", "Bo", "Hana"}
	index, found := findName(names, "Bo")
	fmt.Println(index, found)
}

Drop a result with the blank identifier

The blank identifier takes the remainder here. Only the quotient is kept and printed.

package main

import "fmt"

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

func main() {
	q, _ := divide(17, 5)
	fmt.Println(q)
}

Named return values

The split function names its results bills and coins. A bare return sends both named values back.

package main

import "fmt"

func split(total int) (bills int, coins int) {
	bills = total / 10
	coins = total % 10
	return
}

func main() {
	bills, coins := split(27)
	fmt.Println(bills, coins)
}

Example

package main

import "fmt"

func splitAmount(total int) (int, int) {
	return total / 20, total % 20
}

func main() {
	bills, coins := splitAmount(47)
	fmt.Println("Bills:", bills)
	fmt.Println("Coins:", coins)
}

Key points

  • A function that returns two values lists both types in one pair of parentheses.
  • A call with two results needs two variables on the left of the assignment.
  • The results arrive in the order the return line lists them.
  • Use the blank identifier to drop a result that is not needed.
  • Named return values give each result a name in the function header.
  • A bare return sends the named results in their listed order.

In this example, splitAmount divides 47 by 20 and returns the quotient and the remainder. Main stores the two results in bills and coins. The print lines label each result as it prints.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What does q, _ := divide(17, 5) keep from the two results?