Go functions can return one or more values. Classical programming languages often only have zero or at most one return value.

Variables typically only exist in the function scope, but if they are returned they can be used in the program.

Download PDF

Example

Multiple return

A function that returns two values below:

1
2
3
func values() (int, int) {
return 2,4
}

The first line defines the parameters (there are no paramaters), then it shows the function the datatype to return. A function can have both multiple return variables and multiple parameters.

Beware of the round brackets: twice.

Then the function can be called and both values can be stored in new variables:

1
x, y := values()

The full code:

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

func values() (int, int) {
return 2,4
}

func main() {
x, y := values()
fmt.Println(x)
fmt.Println(y)
}

Exercise

  1. Change the return values from 2,4 to “hello”,”world”. Does it still work?
  2. Can a combination of strings and numbers be used?