liveBook · Manning

Naked return

As explained in 100 Go Mistakes and How to Avoid Them

A naked return is a Go return statement that omits result expressions and returns the current values of the function's named result parameters.

A naked return omits result expressions and returns the current values of named result parameters. Those parameters begin with their zero values, so returning before assigning an error can silently return nil. section 6.2 section 6.3

The unassigned-error trap

In getCoordinates, `return 0, 0, err` returns nil when `ctx.Err() != nil` because the named err parameter was never assigned. Assigning with `if err = ctx.Err(); err != nil { return }` makes the naked return use the updated error. However, mixing naked returns with returns containing arguments is discouraged here; `if err := ctx.Err(); err != nil { return 0, 0, err }` is the clearer fix. section 6.3

func f(a int) (b int) {    #1
    b = a
    return                 #2
}

A minimal function shows the required pairing: the named result parameter receives a value, and `return` returns that current value. section 6.2

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines the syntax and traces a nil-error bug, then contrasts explicit and naked-return fixes.
Examples
Uses a coordinate method, context cancellation, an error result, and a minimal integer-returning function.
What it assumes
Assumes familiarity with Go functions and result parameters while explaining named results and zero-value initialization.
What you can do after
Diagnose unintended zero-value returns and choose between explicit returns and a carefully placed naked return.
How it connects
Connects naked returns with named result parameters, zero values, variable shadowing, and error handling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.