Understand the contract

defer schedules a function call to run when the enclosing function returns. Use it after acquiring a resource successfully so cleanup stays close to acquisition. Multiple deferred calls run in reverse order. A defer belongs to the surrounding function, even when written inside an if block or loop.

The deferred function value and its arguments are evaluated when the defer statement executes. A closure can instead read a captured variable when the closure finally runs. This difference matters for logging, cleanup parameters and code that updates a result before returning.

Work through the example

The example first prints body 2. Deferred calls then execute in reverse order: closure 2 and argument 1. The direct Println argument captured the initial integer value, while the closure reads the variable after it has changed. Neither deferred call runs immediately at its declaration.

package main

import "fmt"

func main() {
    value := 1
    defer fmt.Println("argument", value)
    defer func() { fmt.Println("closure", value) }()
    value = 2
    fmt.Println("body", value)
}

Watch this boundary

Deferring file closure inside a loop can leave every file open until the whole function exits. Move one iteration’s resource work into a helper function or close explicitly after each iteration. Also inspect close errors when they can report a failed write; merely scheduling Close does not handle that failure.

Practice with a changed input

Add a third deferred print and predict the complete order. Then write a helper that opens and closes one resource per call rather than retaining many resources in one loop.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services