BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Defer

Go 1.23

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 by defer f.Close()
  • mu.Lock() followed immediately by defer mu.Unlock()
  • Capturing start time and deferring a logging function to measure execution duration

Code Breakdown

7
defer fmt.Println("world") schedules this print statement. It will not run now; it waits until main() is about to return. Arguments to deferred functions are evaluated immediately, but the function call itself is delayed.
9
"hello" is printed immediately. The output so far is just "hello".
14-16
We loop 4 times, deferring a print of 'i' each time. These are pushed onto the stack: [print(0), print(1), print(2), print(3)].
End
When main() finishes, the stack unwinds in LIFO order: print(3), then 2, then 1, then 0. Finally, the very first deferred "world" is printed.