Go · Course navigation

Go Functions and Multiple Return Values

Return more than one value from a function.

On this page
Before you start

Go basics.

  • Return more than one value from a function.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

A Go function declares its parameter types after the names, and the form a, b int shares one type between both. A function can return several values, listed in parentheses, which Go programs use for results plus an error or, as here, a quotient plus a remainder.

The short declaration q, r := divide(17, 5) receives both results. Integer division truncates toward zero, so 17 / 5 is 3 and 17 % 5 is 2.

Code example

Go
package main

import "fmt"

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

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1package main
2
3import "fmt"
4
5func divide(a, b int) (int, int) {
6 return a / b, a % b
7}
8
9func main() {
10 q, r := divide(17, 5)
11 fmt.Println(q, r)
12}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Two int parameters in, two int results out.—
—
The call returns 3 and 2, assigned to q and r.q = 3, r = 2
—
Println separates its arguments with a space.q = 3, r = 2
3 2

Behind the scenes

How Go processes this code

The Go compiler builds an executable. Its runtime starts the main function in package main.

Cost and common mistakes

O(1) time and space.

  • Dividing an int by zero panics at runtime.
  • Every declared variable must be used, otherwise the compiler reports an error. Use _ to discard a result you do not need.

Try it yourself

Predict divide(20, 6).

Reveal answer and reasoning

It returns 3 and 2, so the output is 3 2.

Further reading