juniorGolang
Explain the `defer` keyword.
Updated Apr 28, 2026
Short answer
defer postpones the execution of a function until the surrounding function returns.
Deep explanation
Deferred calls are pushed onto a stack (LIFO - Last In, First Out). The arguments to the deferred function are evaluated immediately, but the function execution is delayed. It guarantees that cleanup code (like closing a file or unlocking a mutex) runs regardless of how the function exits (return or panic).
Real-world example
Closing database connections, releasing network sockets, or unlocking a Mutex immediately after locking it to prevent deadlocks.
Common mistakes
- Putting `defer` inside a tight loop, which can exhaust stack memory or delay cleanup until the entire function exits, not the loop iteration.
Follow-up questions
- What order do multiple defers execute in?