Go by Example: Defer
Ensure function calls are performed later in a program's execution, usually for cleanup purposes. This example demonstrates the LIFO execution order of deferred calls and their common use cases.
Code
package main
import "fmt"
func main() {
// defer schedules a function call to be run after the function completes
defer fmt.Println("world")
fmt.Println("hello")
// Deferred calls are executed in Last-In-First-Out order
fmt.Println("counting")
for i := 0; i < 4; i++ {
defer fmt.Println(i)
}
}Explanation
The defer keyword schedules a function call to be executed immediately after the surrounding function returns, but before the return value is passed to the caller. This mechanism is primarily used for resource cleanup, such as closing files, releasing mutex locks, or closing database connections, ensuring these actions happen regardless of whether the function returns normally or panics.
Crucially, deferred calls are stored in a stack and executed in Last-In, First-Out (LIFO) order. This means the most recently deferred function runs first. This behavior is intuitive for cleanup: if you open resource A and then resource B, you typically want to close B before closing A.
Common patterns:
f, _ := os.Open(...)followed immediately bydefer f.Close()mu.Lock()followed immediately bydefer mu.Unlock()- Capturing start time and deferring a logging function to measure execution duration

