Named returns
Named returns declare result variables in the function signature. A bare return yields those variables. Deferred closures can assign to them after the return statement has started.
Detailed Explanation
func load(path string) (data []byte, err error) names the two results. Inside the function, data and err exist as local variables, already zeroed. return without values sends whatever they currently hold. return data, err does the same thing with the names written out.
Why name them. Documentation: the caller of func Split(s, sep string) (before, after string) can read the signature and know which string is which. Defer: a deferred closure can set err from f.Close() after the function body has decided to return, which is the correct way to surface a write-flush failure.
Bare return is the controversial part. A long function with several return statements that list no values is hard to follow: you must remember what err holds on each path. The Go wiki's advice is to use named results when they clarify, and still write return data, err when the function is more than a screenful. Many style guides ban bare returns except next to defer.
Shadowing is the actual bug. data, err := os.ReadFile(path) inside a function that already named data and err as results declares new locals if you use := in an inner block, or redeclares in the same block. A bare return then returns the outer zeros, not the file you just read. = assigns to the named results; := may not.
Named results are initialized to zero. If you return on an error path without setting data, the caller receives nil and the error, which is what you want. If you return on a success path without setting err, the caller receives nil error, which is also what you want. The trap is a path that sets neither and still succeeds.
What it costs. Nothing at runtime. The benefit is the defer plus named err pattern for Close. The cost is shadowing and unreadability. If you do not need a deferred assignment, unnamed results and explicit return v, err are clearer.
Code Examples
package main
import (
"fmt"
"os"
)
func writeAll(path string, data []byte) (err error) {
f, err := os.Create(path)
if err != nil {
return err
}
defer func() {
if cerr := f.Close(); err == nil {
err = cerr
}
}()
_, err = f.Write(data)
return err
}
func main() {
fmt.Println(writeAll("/tmp/out", []byte("ok")))
}func splitHostPort(s string) (host string, port string) {
// documented names; still return them explicitly
for i := len(s) - 1; i >= 0; i-- {
if s[i] == ':' {
return s[:i], s[i+1:]
}
}
return s, ""
}func shadowed(path string) (data []byte, err error) {
if path != "" {
data, err := os.ReadFile(path) // new locals in this block
_ = data
_ = err
}
return // zeros, not the file
}Common Gotchas
Bare `return` hides what is being returned
write the values on `return` unless a deferred closure must mutate a named result.
Named results are ordinary locals
they can be assigned, taken by address, and captured by closures. A deferred closure that captures `err` sees the current value at run time, not at `defer` time, if it reads the variable rather than a copy.
The names are in scope for the whole function, including `defer`
that is the feature that makes `Close` error handling work.