How does defer work in Go and what are the common pitfalls?
Assesses fundamental understanding of Go conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
defer schedules a function call to run when the surrounding function returns. Deferred calls run in LIFO order and are typically used for cleanup such as closing files and unlocking mutexes.
f, err := os.Open("data.txt")
if err != nil {
return err
}
defer f.Close()
mu.Lock()
defer mu.Unlock()
Pitfalls to know:
- Arguments are evaluated when the
deferstatement runs, not when the deferred call runs.defer fmt.Println(i)captures the currenti. - Deferred functions can read and modify named return values, which enables error wrapping patterns.
- A
deferinside a long loop accumulates until the function returns, potentially leaking file descriptors. Wrap the body in a closure or close explicitly.
for _, p := range paths {
func() {
f, _ := os.Open(p)
defer f.Close()
}()
}
Deferred calls run even when the function panics, which makes them reliable for releasing resources.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.