Golang Program that Uses Multiple Return Values

To assign multiple return value function to new and old variables in Go, use the short variable declaration syntax (:=) for new variables and regular assignment (=) for existing ones. The := operator is used to simultaneously declare and assign a variable.

package main

import "fmt"

func main() {
  a, b := 1, 2

  // Call a function that returns multiple values and assign
  // the result to a new variable (c) and an existing variable (b)
  b, c := sumAndDifference(a, b)

  fmt.Println("Sum:", b)
  fmt.Println("Difference:", c)

func sumAndDifference(a, b int) (int, int) {
  sum := a + b
  difference := a - b
  return sum, difference


Sum: 3
Difference: -1

In this code example, we have a function sumAndDifference() that returns two values, the sum and the difference of its input parameters.

We then assign the sum to the existing variable b and the difference to a new variable c.

You must declare at least one new variable using the short variable declaration syntax (:=); otherwise, you’ll get a compilation error.