Welcome To Golang By Example

Returning Multiples values from a function in Go (Golang)

Overview

A function is a group of statements that perform a specific task.

Signature of a function

func func_name(input_parameters) return_values{
  //body
}

A function in Golang can return multiple values. An example of a function. The below function is

func f(a int, b int) int {
  return a + b 
}

Return Values

func sum_avg(a, b int) (int, int)
func sum(a, b int) (int, error)
result, err := sum(2, 3) 

Code:

package main

import "fmt"

func main() {
    sum, avg := sum_avg(4, 2)
    fmt.Println(sum)
    fmt.Println(avg)
}

func sum_avg(a, b int) (int, int) {
    sum := a + b
    avg := (a + b) / 2
    return sum, avg
}

Output:

6
3

Named Return Values

A go function can have named return values. With named return values , the return values did not need to be initialised in the function. The named variables are specified in the signature itself. Without named values,  only return type is specified. It is also ok to name some of the return values. For other return values only type can be specified. 

func sum(a, b int) (result int)
func sum_avg(a, b int) (sum int, avg int)
func sum_avg(a, b int) (sum, avg int)

Code:

package main

import "fmt"

func main() {
    sum, avg := sum_avg(4, 2)
    fmt.Println(sum)
    fmt.Println(avg)
}

func sum_avg(a, b int) (sum, avg int) {
    sum = a + b
    avg = (a + b) / 2
    return
}    

Output

6
3