Avoid Typed Nil Interfaces (err != nil Traps) in Go
Why returning a typed nil pointer as an error makes err != nil evaluate to true, and how returning untyped nil fixes it.
By the end of this tutorial you will know:
- What a Go interface actually holds under the hood (type + value)
- Why
var err *MyError = nilreturned aserroris not equal tonil - How to avoid the trap cleanly in custom error functions
Prerequisites: Go 1.20+ installed and basic familiarity with Go error values.
1. The big idea
In Go, an interface value is a two-word box: (concreteType, concreteValue). An interface is only equal to nil when both halves are empty.
If you put a typed nil pointer (like (*MyError)(nil)) into an error interface, the box now holds (*MyError, nil). Its type is not empty, so err != nil evaluates to true.
2. Reproducing the trap
package main
import "fmt"
type MyError struct {
Msg string
}
func (e *MyError) Error() string {
return e.Msg
}
func riskyCheck(ok bool) error {
var err *MyError // nil pointer of type *MyError
if !ok {
err = &MyError{Msg: "something broke"}
}
return err // wraps (*MyError, nil) into error!
}
func main() {
if err := riskyCheck(true); err != nil {
fmt.Println("Unexpected error:", err) // prints <nil>!
}
}Unexpected error: <nil>Even worse, if the caller tries to inspect a field on err or call a method that dereferences e.Msg, the program panics with a nil pointer dereference.
3. The fix: always return untyped nil
Never declare a concrete custom error pointer and return it at the bottom of a function. Return nil explicitly when nothing went wrong, or declare var err error.
package main
import "fmt"
type MyError struct {
Msg string
}
func (e *MyError) Error() string {
return e.Msg
}
func safeCheck(ok bool) error {
if !ok {
return &MyError{Msg: "something broke"}
}
return nil // untyped nil: (nil, nil)
}
func main() {
if err := safeCheck(true); err != nil {
fmt.Println("Unexpected error:", err)
return
}
fmt.Println("All good!")
}All good!Run go run fixed.go. It prints All good! because safeCheck(true) returns a true (nil, nil) interface.
4. Common pitfalls
| Mistake | Symptom | Fix |
|---|---|---|
Returning var e *CustomErr as error | err != nil is true when no error occurred | Return explicit nil on success |
Checking reflect.ValueOf(v).IsNil() everywhere | Slow, noisy code | Fix the return site to return untyped nil |
5. What you learned
You now understand why Go's (type, value) interface representation makes typed nil pointers non-nil, and how returning explicit untyped nil eliminates the bug.