Defer Basics
Fast recall
Quick revision
Core answer
Whether you understand Defer Basics beyond memorized syntax.
Giving a definition without explaining a practical trade-off.
Connect the concept to a small production example and state its complexity or failure mode.
Interview-ready guide
Interview answer
A defer statement registers a function call for later — specifically, at the moment the enclosing function returns, however it returns (normal, early, panic):
func main() {
defer fmt.Println("deferred 1")
defer fmt.Println("deferred 2")
fmt.Println("body")
// prints: body, deferred 2, deferred 1 — LIFO
}Executed. Two defers, registered in order — they run in REVERSE (stack order — the runtime pushes them onto the function's defer stack).
The argument evaluation subtlety — the interview question inside the question:
Defer Basics
Direct Answer
defer schedules a function call to run when the SURROUNDING function returns — LIFO order (last deferred runs first). The call's arguments are evaluated at defer time; the body runs at return time.
Deep Dive & Architecture
i := 0
defer fmt.Println("defer saw:", i) // argument evaluated NOW: 0
i = 10
// at return, prints "defer saw: 0" — args were captured at defer time
Executed. The deferred call's ARGUMENTS are evaluated when defer executes; the call's BODY runs at return. If you need the later value, defer a closure: defer func() { fmt.Println(i) }() — the closure sees the variable at return time.
What defer is FOR: cleanup that must happen on every exit path — closing files, unlocking mutexes, closing channels, recovering panics. Without defer, every return statement needs the cleanup duplicated; with it, the cleanup is registered at acquisition and runs automatically. That's the resource-safety idiom: open, defer close, use.
Common Mistakes & Pitfalls
Giving a definition without explaining a practical trade-off.
Check your understanding
Answer these without looking back at the article.
- When would you use Defer Basics in a real project?
- How would you compare Defer Basics with an alternative?
- What is a common mistake when using Defer Basics?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.