Reading — step 1 of 7
Learn
Go functions can return MULTIPLE values — and the standard idiom for error handling uses this. Effective Go highlights multiple return values as one of Go's unusual features — they sidestep the need for exceptions while keeping callers honest about failures.
Returning multiple values
Declare them in parens after the parameter list. Returns are positional and parallel.
Named return values
For self-documenting signatures:
Named returns serve as docs and let you use a bare return (with the current values of the named variables). Use sparingly — long functions with naked returns are confusing.
The error-pair idiom
Idiomatic Go's error handling:
The convention:
- Last return value is
error - On success, return values + nil
- On failure, return zero values + a non-nil error
- Caller checks
if err != nilimmediately
This pattern is everywhere in Go — os.Open, json.Unmarshal, http.Get, strconv.Atoi, etc.
Discarding returns with _
When you don't need a value, use _:
Don't ignore errors lightly — _ for an error is a code smell unless you genuinely cannot recover.
fmt.Errorf and %w
fmt.Errorf creates a formatted error. The %w verb (Go 1.13+) wraps an underlying error, letting errors.Is and errors.As peer through it:
Wrap errors as they propagate up, building useful error chains.
panic and recover (briefly)
For truly unrecoverable situations (programmer errors), Go has panic:
panic unwinds the stack. recover (only in deferred functions) can catch it. In application code, prefer returning errors over panicking. Reserve panic for invariants you've checked yourself.
Common mistakes
- Ignoring errors with
_— silently corrupts data. At minimum, log them. - Returning generic
errors.Newstrings — hard to match in callers. Usefmt.Errorf("...: %w", err)to wrap. - Naked returns in long functions — readers don't know what's being returned. Use explicit
return min, max. - Using panic for normal errors — exception-style flow surprises Go callers. Stick to error returns.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…