Named Return Values
Fast recall
Quick revision
Core answer
Whether you understand Named Return Values 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
The declaration:
func split(sum int) (x, y int) {
x = sum * 2 / 3 // assign directly — no :=
y = sum - x
return // naked return — returns x and y
}
split(10) // 6, 4 — executedWhat named returns give, each with its moment:
- 1
Zero-initialized: x and y START at 0 — the signature declares and initializes. In a function building an error result gradually,
errstarts nil and is only set on failure — the failure paths return without explicitly naming err. - 2
Naked return — return with no arguments returns the named values. Readability rule: naked returns are clear in SHORT functions (the split above); in long ones they hide which values are being returned — the community style is explicit returns except for short/obvious bodies.
Named Return Values
Direct Answer
Named returns declare the return variables IN the signature: func f() (result int, err error). They're initialized to zero, can be assigned throughout the function, and allow the naked return. Use for: documentation, defer modification, and clarity in multi-return functions.
Deep Dive & Architecture
- Defer modification — THE killer use (the defer topic's core): a deferred function can read and WRITE the named returns. The cleanup/inspect pattern:
func get() (result int, err error) {
defer func() {
if err != nil { result = 0 } // scrub on failure
}()
result, err = doWork()
return
}
Without the NAME, the defer couldn't touch the return value — this pattern REQUIRES named returns.
- Documentation: func Read(p []byte) (n int, err error) — the docs reference n and err by name — godoc shows them; callers read what each value IS.
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 Named Return Values in a real project?
- How would you compare Named Return Values with an alternative?
- What is a common mistake when using Named Return Values?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.