Why a Typed Nil Pointer Is Not == nil in Go Interfaces
Reproduce Go's typed-nil interface trap with custom errors and io.Writer, see why w == nil returns false, and fix return paths cleanly. After this, custom error helpers never return phantom non-nil errors.
Skip ahead: If you already know an interface holds a (type, value) pair, skip to "Case 2: custom error helpers returning a typed nil" or the comparison table below.
Your function returns an empty custom error pointer, and yet if err != nil triggers in the caller and aborts the request. Nothing is wrong with !=—in Go, an interface value is only nil when both its concrete type and its underlying value are nil. Passing a typed nil pointer fills the type slot, so err == nil evaluates to false. Verified on golang:trixie (Go 1.27.4).
Case 1: io.Writer and custom error return values
This program shows the exact same trap twice: first with a nil *bytes.Buffer assigned to io.Writer, and second with a custom *ValidationError returned as error:
package main
import (
"bytes"
"fmt"
"io"
)
type ValidationError struct {
Field string
}
func (e *ValidationError) Error() string {
return "invalid " + e.Field
}
func validateBad(name string) error {
var err *ValidationError
if name == "" {
err = &ValidationError{Field: "name"}
}
return err
}
func validateGood(name string) error {
if name == "" {
return &ValidationError{Field: "name"}
}
return nil
}
func main() {
var buf *bytes.Buffer = nil
var w io.Writer = buf
fmt.Printf("typed nil io.Writer == nil: %t\n", w == nil)
err1 := validateBad("ana")
fmt.Printf("validateBad(\"ana\") == nil: %t (type=%T)\n", err1 == nil, err1)
err2 := validateGood("ana")
fmt.Printf("validateGood(\"ana\") == nil: %t\n", err2 == nil)
}
typed nil io.Writer == nil: false
validateBad("ana") == nil: false (type=*main.ValidationError)
validateGood("ana") == nil: true
Look at validateBad("ana"): err was never assigned, so its pointer value was nil, yet return err boxed (*main.ValidationError, nil) into the error interface. In the caller, err1 == nil is false—and worse, calling err1.Error() will panic if the method dereferences e.Field on that nil pointer.
Case 2: why Go's interface layout behaves this way
Under the hood, an interface value in Go is a two-word pair: (concrete type, value). When you write return nil, Go builds (nil, nil), which equals nil. When you return a typed pointer variable var err *ValidationError, Go builds (*ValidationError, nil), which does not equal (nil, nil).
Case 3: optional io.Writer or logger dependencies
The same bug happens when a helper accepts an optional io.Writer or custom interface:
- If a caller passes
var buf *bytes.Buffer(stillnil) intowriteReport(w io.Writer), your guardif w != nilpasses, andw.Write(...)then panics or fails unexpectedly. - Fix at the call site: always pass untyped
nilwhen an optional dependency is absent (writeReport(nil)), or initialize the concrete value (var buf bytes.Buffer; writeReport(&buf)).
Case 4: return error explicitly, not a concrete pointer
Inside any function whose signature returns error:
- Declare
var err errorif you accumulate an error across branches, nevervar err *MyCustomError. - Even better, return early with
return nilon the happy path andreturn &MyCustomError{...}only inside the failure branch, just likevalidateGoodabove.
Safe vs. unsafe patterns
| Pattern | Value inside interface | iface == nil |
|---|---|---|
return nil | (nil, nil) | true (safe) |
var err error; return err | (nil, nil) | true (safe) |
var err *MyErr; return err | (*MyErr, nil) | false (broken!) |
var buf *bytes.Buffer; fn(buf) | (*bytes.Buffer, nil) | false (broken!) |
⚠ Warning: Do not try to work around a typed nil by using reflect.ValueOf(w).IsNil() inside every function. Fix the return statement or caller instead—returning untyped nil keeps every standard if err != nil check honest.
Common mistakes
- Returning a concrete error struct pointer from a helper: changing a function's return type from
*MyErrortoerrorwithout changingvar err *MyErrorturns everynilreturn into a non-nil interface. - Calling
e.FieldinsideError()without anilcheck: if a typednilever slips through and a logger callserr.Error(), readinge.Fieldpanics with a nil-pointer dereference.
What happens if you skip this
A validation helper returns err != nil for valid inputs, rejecting every user request—or a logger calls err.Error() on a typed nil pointer and crashes the handler with a nil-pointer panic.
Related course: Go Intermediate.
About
Reproduce Go's typed-nil interface trap with custom errors and io.Writer, see why w == nil returns false, and fix return paths cleanly. After this, custom error helpers never return phantom non-nil errors.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.