Deferred calls
- Version
- 1.27
- Review
- Draft
Summary#
A defer registers a call to run when its surrounding function returns or unwinds because of a panic. Deferred calls run in reverse order of registration.
Syntax#
resource, err := openResource()
if err != nil {
return err
}
defer resource.Close()
Example#
package main
import "fmt"
func main() {
label := "start"
defer fmt.Println("recorded:", label)
defer func() { fmt.Println("current:", label) }()
label = "finish"
fmt.Println("body:", label)
}
Expected output#
body: finish
current: finish
recorded: start
Common mistakes#
A deferred call evaluates its arguments at registration time. A closure can read the current variable later. Inside a long loop, move each iteration's work into a helper function when its cleanup should happen before the loop advances. os.Exit terminates the process without running deferred calls.
Version applicability#
This use of defer applies to Go 1.27 and earlier Go versions.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0