Named Return Values
Go allows you to name the return values in a function’s signature. This treats the return values as variables defined at the top of the function.
Documentation and Clarity
Naming return values helps document the purpose of the output without needing extra comments.
func getCoords() (x, y int) {
// x and y are initialized to 0
x = 10
y = 20
return // automatically returns x and y
}
Naked Returns
A return statement without arguments is called a naked return. It automatically returns the current values of the named return parameters.
[!WARNING] Naked returns should only be used in short, simple functions. In longer functions, they can make the code harder to read because the return values aren’t explicitly listed.
Explicit Returns
You can still return values explicitly even if they are named:
func getCoords() (x, y int) {
return 5, 6 // Overwrites named values and returns 5, 6
}