Go core · 3 MIN READ
A return can name what it is handing back
Write a short function that uses a naked return, and know when not to.
Names in a function's result list declare local result variables initialized to zero. A bare return returns their current values. In a short helper, names such as quot and rem can explain which result is which.
An explicit return quot, rem is often easier to review once a function has branches. Result names document intent, but the compiler does not protect two same-typed results from being swapped. A deferred closure may change named results before the function returns to its caller.
SEE THE IDEA
Named results are local variables
- 01
Signature
gofunc split() (a, b int)Declares result variables
- 02
Body
goa = 2Assignments update those variables
- 03
Return
goreturn a, bExplicit values keep the exit clear
A bare return returns the current named result values.
In practice
Use result names when they explain a pair of similar types, such as a lower and upper bound. They begin at their zero values and remain in scope for the body. An explicit return is often easier to review than a bare return once the function has branches.
Watch out
A deferred closure can change named results before the caller receives them. That is useful, but deserves a visible contract.
Work through the exercise
package main
// Split returns n / d and n % d. Name the results and use a
// naked return. Do not guard against d == 0; the test never
// passes zero.
func Split(n, d int) (int, int) {
return 0, 0
}
func main() {}Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.
Progress stays in this browser. No account needed.