Skip to content
Multiple Returns and the error Pattern
step 1/7

Reading — step 1 of 7

Learn

~3 min readPointers and Errors

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

go

Declare them in parens after the parameter list. Returns are positional and parallel.

Named return values

For self-documenting signatures:

go

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:

go

The convention:

  1. Last return value is error
  2. On success, return values + nil
  3. On failure, return zero values + a non-nil error
  4. Caller checks if err != nil immediately

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 _:

go

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:

go

Wrap errors as they propagate up, building useful error chains.

panic and recover (briefly)

For truly unrecoverable situations (programmer errors), Go has panic:

go

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.New strings — hard to match in callers. Use fmt.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…