← Back to Go Course | Chapter 4: Functions | Lesson 3 of 7

Named Return Values

Named returns let a function pre-label its answer boxes at the top, so a plain return at the end automatically sends back whatever is inside them.

Declaring Named Returns

Instead of only listing return types, a function can give each return value a name in the signature, which both documents its purpose and pre-declares it as a usable local variable initialized to its zero value.

Example: Declaring Named Returns

markup
package main

import "fmt"

func rectangleStats(w, h float64) (area, perimeter float64) {
	area = w * h
	perimeter = 2 * (w + h)
	return
}

func main() {
	a, p := rectangleStats(4, 3)
	fmt.Println("area:", a, "perimeter:", p)
}

Bare return Statements

When return values are named, a plain return with no arguments automatically returns whatever those named variables currently hold, saving you from repeating the variable names.

Note: A bare return can make short functions terse, but for long functions an explicit 'return area, perimeter' is often clearer.

Example: Bare return Statements

markup
package main

import "fmt"

func splitName(full string) (first, last string) {
	first = "Go"
	last = "Pher"
	return
}

func main() {
	f, l := splitName("gopher")
	fmt.Println(f, l)
}

Named Returns with error

Named returns are especially common for the value/error pattern, where naming the error variable err makes the function body read naturally as you set it inside conditionals before returning.

Example: Named Returns with error

markup
package main

import (
	"errors"
	"fmt"
)

func validateAge(age int) (valid bool, err error) {
	if age < 0 {
		err = errors.New("age cannot be negative")
		return
	}
	valid = true
	return
}

func main() {
	ok, err := validateAge(-3)
	fmt.Println(ok, err)
}
Common Mistakes
  1. Overusing named returns in long functions, which makes it hard to track where each named value actually gets set.
  2. Shadowing a named return variable with := inside the function body, creating a separate local variable that a bare return won't pick up.
  3. Assuming named returns are required for multiple return values -- they're just an optional documentation/convenience feature.
Chapter Summary
  • Named return values give return parameters names right in the function signature.
  • A bare return with no arguments sends back the current values of the named returns.
  • Named returns act as pre-declared, zero-valued local variables inside the function.
  • They're most useful for short functions and for documenting what each return value means.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.