defer
defer schedules a call to run right before the surrounding function returns, no matter which return statement triggers it — including one triggered by a later panic. It's overwhelmingly used for cleanup:
func readFile(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
// ... use f ...
return nil
}Reading top to bottom: open the file, and immediately say "close it when this function ends" — right next to the open, not scattered across every possible early-return path further down. That proximity is the whole value: in a function with several if err != nil { return err } early exits, remembering to close a resource before each one is exactly the kind of thing that's easy to miss. One defer, right after the resource is acquired, covers every exit path automatically.
Deferred calls run in last-in-first-out order if there are several, and their arguments are evaluated immediately (at the defer line), even though the call itself happens later.