Go by Example

Defer

Schedule cleanup and other calls to run when the current function returns.

The defer statement schedules a function call for when the current function returns, including during panic unwinding. Deferred calls run in last-in, first-out order. Arguments are evaluated when defer runs.

The second call is deferred last, so it runs first after the function body finishes.

package main
 
import "fmt"
 
func main() {
    defer fmt.Println("first")
    defer fmt.Println("second")
    fmt.Println("body")
}

In production

Defer cleanup immediately after acquiring a resource, such as closing a file or unlocking a mutex. A defer inside a loop runs only when the enclosing function returns, so move each iteration's work into a helper when cleanup must happen before the next iteration.

Enjoyed this? Get more software craft delivered to your inbox.