ProgrammingSenior Go Developer

How do named return values work in Go? What are the advantages and dangers associated with their use, and what are the features of zero values in this context?

Pass interviews with Hintsage AI assistant

Answer

In Go, you can explicitly declare names for return values in the function signature. Such values are automatically initialized to their type's zero value. This is convenient when working with a large number of return variables and allows for implicit "returning" of values via the return statement (without arguments).

Example:

func foo() (x int, err error) { if someCheck() { x = 1 return // will return (1, nil) } return // will return (0, nil), if x and err were not explicitly assigned }

Details:

  • If you forget to explicitly assign an error to the variable, its zero value will be returned (usually nil for error). This can mask errors in logic.
  • Zero values for named results are used for initialization and default return.
  • Use named results with caution: they enhance readability only where returning from the function has an unambiguous meaning.

Trick Question

What will a function with named results return if there are no assignments to the return variables and simply return is called?

Answer: Their zero values will be returned. For example, for int — 0, for pointer — nil. Example:

func test() (res *MyType, code int) { return // the same as "return nil, 0" }

Examples of Real Errors


Story

In a financial service, the variable err (error) was forgotten to be assigned a value inside a function with named returns. As a result, when a failure occurred, the function returned nil, and the error was lost. Consequently, transaction processing broke down, and some operations went unnoticed.


Story

During refactoring, a new named return result was added, but compatibility with the previous return type was not noticed — tests missed the problem due to returning a zero value, leading to a silent bug in the storage.


Story

In one of the helper functions, errors were logged through the named result, but sometimes they were forgotten not only during returning but also in logging, which led to hard-to-reproduce bugs ("error lost").