Home >Backend Development >Golang >Go Named Returns vs. Normal Returns: Why Does Panic Handling Differ?
In Go, named result parameters allow assigning specific values to be returned by a function. However, this behavior differs from functions that return without named result parameters, which can raise questions.
Consider the following code, where NormalReturns and NamedReturns are functions that attempt to return an error upon a panic:
func NormalReturns(n int) error { var err error defer catch(&err) panicIf42(n) return err } func NamedReturns(n int) (err error) { defer catch(&err) panicIf42(n) return }
When a panic is raised in panicIf42, NormalReturns returns nil, even though one would expect an error. This occurs because the deferred catch function assigns the error after the panic has returned control to the caller.
In contrast, NamedReturns returns the modified err value because named result parameters allow deferred functions to modify them. When the panic occurs, the deferred catch function assigns the error, which is preserved and returned when the function ends.
Spec for Return Statements:
"All the result values are initialized to the zero values for their type upon entry to the function ... A 'return' statement that specifies results sets the result parameters before any deferred functions are executed."
Spec for Defer Statements:
"Deferred functions may access and modify the result parameters before they are returned."
Therefore, in NormalReturns, since there are no named result parameters, the return value is initialized to nil and remains nil after the panic. In NamedReturns, the deferred function modifies the err result parameter, and its value is used as the returned error.
The above is the detailed content of Go Named Returns vs. Normal Returns: Why Does Panic Handling Differ?. For more information, please follow other related articles on the PHP Chinese website!