點燈坊

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

Named Return Values

Sam Xiao's Avatar 2022-03-26

Go’s return values may be named. If so, they are treated as variables defined at the top of the function.

Version

Go 1.18

Normal Function

package main

import "fmt"

func main() {
  a, b := split(19)
  fmt.Println(a, b)
}

func split(x int) (int, int) {
  y := x / 10
  z := x % 10
  return y, z
}

Line 10

func split(x int) (int, int) {
  y := x / 10
  z := x % 10
  return y, z
}

y and z are return values, but we have to define them first and then return them as usual

named000

Named Return Values

package main

import "fmt"

func main() {
  a, b := split(19)
  fmt.Println(a, b)
}

func split(x int) (y, z int) {
  y = x / 10
  z = x % 10
  return
}

Line 10

func split(x int) (y, z int) {
  y = x / 10
  z = x % 10
  return
}
  • (y, z int) : return values are defined in the return type list
  • return : a return statement without arguments returns the named return values. This is known as a naked return

named001

Conclusion

  • Naked return statements should be used only in short functions. They can harm readability in longer functions

Reference

A Tour of Go, Named return values