Use named results
Use named results
You may give result parameters names in the signature. These names are local variables initialized to their type’s zero value. A bare return returns their current values; an explicit return can still be used. Choose the form that makes the returned values clear.
package main
import "fmt"
func dimensions() (width, height int) { width = 3; height = 4; return }func main() { w, h := dimensions() fmt.Println(w, h)}width and height begin at zero, then receive 3 and 4. The caller is free to name its variables differently. Result names are not required at the call site.
Prefer explicit returns for clarity
package main
import "fmt"
func sign(n int) (negative, zero bool) { return n < 0, n == 0 }func main() { fmt.Println(sign(-2)) fmt.Println(sign(0))}Named results can document meaning even with an explicit return. In fmt.Println(sign(-2)), the sole argument is a call whose two results become two arguments to Println. Be careful not to shadow a result with a same-named local variable in a nested block; a bare return in that scope can be rejected. Avoid long functions with bare returns whose values are hard to trace.
Try it locally
Write stats(n int) (twice, square int) assigning both named results then using bare return. Print stats(5) and stats(0).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functions 04: Use named results
Check the lesson objective before moving on.
What is the initial value of a named int result?
Can named-result functions use explicit return expressions?