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:
nil for error). This can mask errors in logic.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" }
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").