-
Notifications
You must be signed in to change notification settings - Fork 18.3k
Description
Context: https://tour.golang.org/basics/7
For me as newcomer the language the the sentence:
A return statement without arguments returns the current values of the results. This is known as a "naked" return.
does not really explain what a naked return is. Does it return all calculated values of a function? or just the last two used values? or the ones that have the same names as in the return values? What happens if I have another variable in the function is it also returned?
Not sure if anyone agrees, while thinking about it and trying code in the browser I quickly found what works and what doesn't.
I first tried:
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
z = x * x
return
}
Doesn't compile, because z is not defined, got me "aha , so x, and y are defined in the return statement. (variable declarations are only in the next chapter of the tour, so I peeked ahead and I tried)
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
var z = x * x
return
}
which errors because z is unused. Thats where I figured that return does not just take the last two calculated values but the actual names. Which now makes sense but in the beginning was confusing somehow.
The change could be something like:
The named values defined in the return statement can be used as variables in the function body. In this case they don't need to be specified after the return statement. This is known as a "naked" return.
Cheers,
Henning