Search and navigate

Pages

Start HereRoadmapTutorialsCheatsheetInterview QuestionsResources

Published tutorials

Building a REST API with Go: The Complete TutorialError Handling in Go: Wrapping, Classification, and APIsFan-Out Fan-In in Go: Parallel Work with ChannelsFuzz Testing in Go: Finding Bugs AutomaticallyGeneric Functions in Go: Writing Reusable CodeGo Benchmarking: Measuring Performance with testing.BGo Channel Patterns: Advanced Recipes That WorkGo Channels: Communication Between GoroutinesGo Concurrency Patterns: A Practical CatalogueGo Constraints: comparable, Ordered and Custom SetsGo Context: Cancellation, Deadlines, and Request ValuesGo defer: Cleanup, Ordering, and Common TrapsGo HTTP Client: Timeouts, JSON, and Reliable RequestsGo HTTP Middleware: Build a Production ChainGo Interview Questions: 25 Answers That Show UnderstandingGo Mutex: Protecting Shared State from Race ConditionsGo net/http: Build an HTTP Server from ScratchGo select Statement: Multiplexing Channels ExplainedGo Tools You Need for a Reliable Development LoopGo Tutorial: From First Program to Backend FoundationsGo Type Parameters: Syntax and Constraints ExplainedGo Worker Pool Pattern: Bounded Concurrency at ScaleGo's Type System Deep Dive: Static Typing Done RightGolang Compilation and Execution ExplainedGolang Developer Salary 2026: US, UK and RemoteGolang File Structure for Modules and ApplicationsGolang Hello World and Your First Go ProgramGolang IDEs: Choose an Editor for Your WorkflowGolang Interfaces: What They Are and How to Use ThemGoroutine Leaks in Go: How to Detect and Prevent ThemGoroutines in Go: Concurrency Without LeaksHow to Download and Install Golang SafelyHow to Learn Golang with a Focused Study PlanIntegration Testing in Go: Testing Real BoundariesJSON in Go: Encoding, Decoding, and ValidationLearn Golang with a Practical Beginner CourseMocking in Go: Test Doubles Without Magicsync.WaitGroup in Go: Coordinating Multiple GoroutinesTable-Driven Tests in Go: The Idiomatic WayTesting in Go: Table Tests, HTTP, Fakes, and CoverageWhat Is Go and How Does a Go Program Work?Why Learn Golang and What Is Go Used For?Writing Unit Tests in Go: A Practical Guide
Open full search and filters →

Go defer: Cleanup, Ordering, and Common Traps

Understand Go defer ordering, argument evaluation, named returns, resource cleanup, and loop pitfalls.

Standard-library lessonGo requirement: Go 1.21+How tutorials are checked
Fundamentals · Lesson 17Saved in this browser. No account required.
Three cleanup steps returning in reverse stack order
Deferred calls run in last-in, first-out order when the surrounding function returns. Image: Golang Tutorial

defer schedules a function call to run when the surrounding function returns. It keeps cleanup beside successful resource acquisition.

Close resources reliably

file, err := os.Open(name)
if err != nil {
	return err
}
defer file.Close()

Register the cleanup only after acquisition succeeds. For resources whose close error matters, handle it explicitly rather than discarding it.

Defers run last-in, first-out

defer fmt.Println("first")
defer fmt.Println("second")

This prints second, then first. Stack ordering is useful when later setup depends on earlier resources.

Arguments are evaluated immediately

name := "before"
defer fmt.Println(name)
name = "after"

The deferred call prints before. To read the later value, defer a closure that captures the variable.

Keep loop lifetimes small

Defers run at function return, not the end of a loop iteration. A loop that opens thousands of files and defers every close retains them all. Extract one iteration into a helper function so cleanup happens promptly.

Defer and panic

Deferred calls still execute while a panic unwinds the stack. This makes them appropriate for releasing locks and resources. Recovery should normally happen only at a clear process boundary such as an HTTP middleware, where the failure can be logged and converted to a stable response.

Defer has a small cost, but clarity is usually more valuable. Optimize it away only after measurement proves cleanup scheduling matters in a genuinely hot path.