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
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 listreturn
: areturn
statement without arguments returns the named return values. This is known as anaked
return
Conclusion
- Naked return statements should be used only in short functions. They can harm readability in longer functions