Use defer for cleanup
Use defer for cleanup
Defer schedules a function call to run when its enclosing function returns, including early returns. Register cleanup immediately after successfully acquiring a resource. Do not defer cleanup for a resource that failed to initialize. Deferred calls also run during ordinary panic unwinding, but not every kind of process termination.
package main
import ( "fmt")
func work(fail bool) { fmt.Println("acquire") defer fmt.Println("release") if fail { fmt.Println("early return") return } fmt.Println("work")}func main() { work(true) work(false)}The printed messages simulate a resource lifetime without opening a real file. Both return paths execute the registered cleanup. In real code, call the resource’s documented cleanup method and decide how to handle its errors.
Expected output:
acquireearly returnreleaseacquireworkreleasePreserve cleanup failures
package main
import ( "errors" "fmt")
type Resource struct{}
func (Resource) Close() error { return errors.New("close failed") }func job() (err error) { r := Resource{} defer func() { err = errors.Join(err, r.Close()) }() return errors.New("work failed")}func main() { fmt.Println(job())}This simulated Close returns a failure. The deferred closure runs after the named result err receives the return value, so Join preserves both errors. If both were nil the result would be nil. Do not blindly ignore cleanup errors when they affect correctness. Defers inside long loops accumulate until the surrounding function returns; use a helper per iteration when cleanup must happen sooner.
Expected output:
work failedclose failedTry it locally
Write a function step that prints "start", defers printing "finish", and returns an error "failed". Call it and print the error afterward.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Errors and cleanup 08: Use defer for cleanup
Check the lesson objective before moving on.
When should cleanup be registered after acquiring a resource?
Why use a helper function for resource cleanup inside a long loop?