liveBook · Manning

Named return value

As explained in Go in Practice, Second Edition

Named return values are function results declared with identifiers that can be referenced and assigned within the function body.

Named return values declare function results with identifiers, making those results available for assignment inside the function body. A return statement without expressions, called a naked return, returns their current values. Callers use the function exactly as they would use unnamed results, including assigning unwanted results to _. section 1.2.1

Listing 1.2 Named return values
package main

import (
    "fmt"
)

func getStrings() (first string, second string) {      #1
    first = "Foo"                      #2
    second = "Bar"                    
    return             #3
}

func main() {
    n1, n2 := getStrings()      #4
    fmt.Println(n1, n2)

The getStrings example names first and second, assigns both inside the function, and returns them implicitly. section 1.2.1

Named results also let deferred closures update what the function returns. This is useful when panic recovery must convert a panic into an error while ensuring resources such as files are closed. Because the closure refers to the named file and err variables, assigning err changes the eventual result. section 4.3.4

Recovering while closing a file

OpenCSV declares (file *os.File, err error), defers a closure, and assigns the recovered panic to err after closing the file. Ordinary callers still receive a file and error pair. section 4.3.4

How Go in Practice, Second Edition covers it

How deep it goes
Explains declaration, assignment, naked return, and deferred-closure interaction, but cautions that longer control flow reduces readability.
Examples
Demonstrates getStrings with first and second results, then OpenCSV converting a recovered panic into an error.
What it assumes
Assumes familiarity with functions, multiple return values, variables, errors, defer, and panic recovery.
What you can do after
Apply named results in Go functions and use them to propagate errors from deferred recovery code.
How it connects
Connects named return values with multiple return values, error handling, defer, closures, panic recovery, and resource cleanup.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.