How defer Works Internally in Go

Go's defer executes deferred functions in LIFO order after the surrounding function returns, with arguments evaluated at the time of deferral.

Go's defer works by pushing a closure containing the deferred function and its captured arguments onto a stack at the moment the statement is executed, then popping and running those closures in Last-In-First-Out (LIFO) order when the surrounding function returns. The arguments are evaluated immediately when the defer statement runs, not when the function exits, ensuring the deferred logic executes with the values present at the deferral point.

func example() {
    x := 1
    defer func() { fmt.Println(x) }() // Prints 1, x evaluated now
    x = 2
} // Deferred function runs here in reverse order of deferral