When would you use Defer Basics in a real project
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 named-return form unlocks defer's most powerful pattern:
func get() (result int) {
defer func() {
result *= 2 // modifies the return value AFTER it was set
}()
result = 5
return // result=5, then defer doubles it → returns 10
}The mechanism, precisely: the function sets result = 5, the return 'happens', then deferred functions run — with access to result (it's a named variable in scope) — and only THEN does the function actually return to its caller. The deferred modification WINS.
The canonical use — error inspection/cleanup:
When would you use Defer Basics in a real project
Direct Answer
If the function has a named return, the deferred function can INSPECT AND MODIFY it. With unnamed returns, the deferred function sees nothing to modify. The mechanism: named returns are variables, and defer runs after the value is set but before the function actually returns.
Deep Dive & Architecture
func load() (data []byte, err error) {
defer func() {
if err != nil {
data = nil // scrub partial data on failure
log.Printf("load failed: %v", err)
}
}()
data, err = os.ReadFile("cfg")
return
}
The defer sees the final error state and acts — cleanup logic written once, running on every exit path.
The unnamed-return contrast: with func get() int, a deferred function can't touch the return value — there's no named variable to reference. That's why the idiom requires named returns, and why 'deferred function modified the return value' only ever comes up with the named form.
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?
- 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.