點燈坊

失くすものさえない今が強くなるチャンスよ

Multiple Return Values

Sam Xiao's Avatar 2022-03-26

Go has built-in support for multiple return values. This feature is used often in idiomatic Go, for example to return both result and error values from a function.

Version

Go 1.18

Multiple Return Values

package main

import "fmt"

func main() {
  a, b := swap(1, 2)
  fmt.Println(a, b)
}

func swap(x, y int) (int, int) {
  return y, x
}

Line 10

func swap(x, y int) (int, int) {
  return y, x
}
  • (int, int) : declare returning 2 int of the function
  • return y, x : return 2 int separated by ,

Line 6

a, b := swap(1, 2)
  • a, b : multiple assignment from the function call

tuple000

Ignore the Return Values

package main

import "fmt"

func main() {
  _, b := swap(1, 2)
  fmt.Println(b)
}

func swap(x, y int) (int, int) {
  return y, x
}

Line 6

_, b := swap(1, 2)
  • _ : use the blank identifier _ to ignore the return value

tuple001

Conclusion

  • Multiple return values in Go is elegant and intuitive, we can also use _ to ignore the return value

Reference

Go by Example, Multiple Return Values