a common mistake when using Defer Basics
Fast recall
Quick revision
Core answer
Practical understanding of Defer Basics.
Repeating a definition without saying when to use it.
Give one trade-off and say how you would test it.
Interview-ready guide
Interview answer
The trap:
func processAll(files []string) error {
for _, name := range files {
f, err := os.Open(name)
if err != nil { return err }
defer f.Close() // WRONG — all closes run when processAll returns
process(f)
}
return nil
}Every f stays open for the entire loop — a thousand files held at once. The defers pile up (each defer is a stack entry) and execute in LIFO order when processAll finally returns.
The fix — scope the defer to the iteration:
for _, name := range files {
if err := processOne(name); err != nil {
return err
}
}a common mistake when using Defer Basics
Direct Answer
defer in a loop accumulates: NONE of the deferred calls run until the FUNCTION returns — not per-iteration. 1000 iterations = 1000 open files held until the function ends. Fix: wrap the body in a function (or closure) so each iteration's defer runs at that function's return.
Deep Dive & Architecture
func processOne(name string) error { f, err := os.Open(name) if err != nil { return err } defer f.Close() // RIGHT — runs when processOne returns return process(f) }
The defer now lives in a function whose return IS the iteration's end — the file closes per-iteration. This 'extract the body' fix is also just better code: the loop reads as dispatch, the helper owns the resource lifecycle.
The alternatives, in honesty: an immediately-invoked closure per-iteration (func() { defer f.Close(); process(f) }()) — same fix, uglier; or explicit close at iteration end (no defer — but then error paths need the close duplicated — the exact problem defer solved). Extracting the function is the idiom the community settled on.
### Common Mistakes & Pitfalls
Repeating a definition without saying when to use it.
Check your understanding
Answer these without looking back at the article.
- What is Defer Basics, and when would you use it?
- When would you use Defer Basics in a real project?
- How would you compare Defer Basics with an alternative?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.