Defer
Schedule cleanup and other calls to run when the current function returns.
defer schedules a function call to run when the current function returns. If several calls are deferred, the last one runs first. Go saves each call's arguments when it reaches the defer statement, not later when the function returns.
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
Schedule cleanup with defer soon after opening a file or locking shared data. A deferred call inside a loop runs only when the surrounding function returns, so put one loop iteration in a helper function if its cleanup must happen before the next iteration.
Enjoyed this? Get more software craft delivered to your inbox.