Go

Fix Typed Nil Interface Bugs and Error Unwrapping in Go

Your service crashes with a nil pointer dereference several layers away from where an error was returned, or an if err != nil check evaluates to true despite the inner function returning a nil pointer. You inspect the return values in the debugger and find a variable that prints as nil inside an error interface wrapper that insists it is not nil.

text
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4b21d5]

goroutine 1 [running]:
main.processTask(...)
    /home/app/worker.go:42
main.main()
    /home/app/main.go:18
exit status 2

Or you get the quieter, more insidious symptom:

text
Task failed unexpectedly: <nil>

The anatomy of typed nil interfaces

An interface in Go is not a single pointer. In the Go runtime, an interface value is represented internally by one of two structs: iface (for interfaces that have methods, like error) or eface (for empty interfaces, any / interface{}).

An iface contains two pointers:

  1. tab: a pointer to an itab, which tracks the interface type and the concrete type implementing it.
  2. data: an unsafe.Pointer to the actual concrete value.

When you compare an interface to bare nil using err != nil, Go does not merely check whether the data pointer is zero. It evaluates whether both the type table pointer and the data pointer are nil. If you assign a concrete pointer that is nil to an interface variable, the interface gets a valid type table pointer pointing to your struct definition, while its data pointer is set to nil. The interface itself is no longer nil.

Here is the exact code pattern that causes this failure:

go
package main

import (
	"fmt"
)

type QueryError struct {
	Query string
	Code  int
}

func (e *QueryError) Error() string {
	return fmt.Sprintf("query failed [%d]: %s", e.Code, e.Query)
}

func runQuery(rawSQL string) *QueryError {
	if rawSQL == "" {
		return &QueryError{Query: rawSQL, Code: 400}
	}
	// Everything is fine, return nil
	var err *QueryError = nil
	return err
}

func execute() error {
	// Returns a concrete *QueryError typed nil into an error interface
	return runQuery("SELECT 1")
}

func main() {
	err := execute()
	if err != nil {
		// This block executes!
		fmt.Printf("Task failed unexpectedly: %v\n", err)
		
		// If you try to inspect specific fields, you crash
		fmt.Printf("Error code: %d\n", err.(*QueryError).Code)
	} else {
		fmt.Println("Success")
	}
}

Running this results in:

text
Task failed unexpectedly: <nil>
panic: runtime error: invalid memory address or nil pointer dereference

execute() has a return type of error. When runQuery returns (*QueryError)(nil), the runtime constructs an interface value where tab points to *QueryError and data is 0x0. That interface is not nil. The check if err != nil passes. Then calling err.(*QueryError).Code attempts to read an offset from a zero address and blows up the runtime.

The fix: return bare nil for interfaces

Never declare concrete pointer types as your primary return variable if the function signature returns an interface. Return bare, untyped nil on success paths.

If the function returns error, make the local variable error, or return nil directly.

go
package main

import (
	"fmt"
)

type QueryError struct {
	Query string
	Code  int
}

func (e *QueryError) Error() string {
	return fmt.Sprintf("query failed [%d]: %s", e.Code, e.Query)
}

// Return the error interface directly, or return bare nil
func runQuery(rawSQL string) error {
	if rawSQL == "" {
		return &QueryError{Query: rawSQL, Code: 400}
	}
	return nil
}

func execute() error {
	return runQuery("SELECT 1")
}

func main() {
	err := execute()
	if err != nil {
		fmt.Printf("Task failed unexpectedly: %v\n", err)
		return
	}
	fmt.Println("Success")
}

If you must keep a helper function that returns the concrete pointer type *QueryError, check for nil before converting it to an error interface at the call boundary:

go
func execute() error {
	qErr := runQuery("SELECT 1")
	if qErr != nil {
		return qErr
	}
	return nil
}

Returning qErr directly when it evaluates to nil forces an interface boxing operation. Returning explicit nil assigns a zeroed iface struct where both tab and data are nil.

Pointer vs value receivers on error types

A related bug happens when implementing Error() string using a pointer receiver versus a value receiver, especially when pairing custom errors with errors.Is and errors.As.

Consider this setup:

go
type NotFoundError struct {
	Resource string
}

func (e *NotFoundError) Error() string {
	return fmt.Sprintf("%s not found", e.Resource)
}

Because Error() has a pointer receiver (e *NotFoundError), the type that implements the error interface is *NotFoundError, not NotFoundError.

go
func findUser(id string) error {
	if id == "" {
		// Compile error: Cannot use 'NotFoundError{...}' (type NotFoundError)
		// as type error: NotFoundError does not implement error
		// (Error method has pointer receiver)
		return NotFoundError{Resource: "user"}
	}
	return nil
}

If you switch Error() to a value receiver to allow returning values:

go
type NotFoundError struct {
	Resource string
}

func (e NotFoundError) Error() string {
	return fmt.Sprintf("%s not found", e.Resource)
}

Both NotFoundError and *NotFoundError now satisfy the error interface. That flexibility introduces subtle equality bugs when checking errors downstream.

Unpacking errors correctly with errors.Is and errors.As

Go 1.13 introduced wrapped errors via fmt.Errorf("...: %w", err). You should never use direct equality (err == ErrNotFound) or direct type assertions (err.(*NotFoundError)) on errors that cross package boundaries, because callers or middleware often wrap them.

Use errors.Is for sentinel errors, and errors.As for error types carrying data. Both inspect the chain created by Unwrap() error.

Gotcha 1: Target pointer indirection in errors.As

The single most common operational error with errors.As is passing the wrong level of pointer indirection. errors.As requires that the second parameter is a non-nil pointer to a type that implements error, or a pointer to an interface.

If your error implementation uses a pointer receiver:

go
package main

import (
	"errors"
	"fmt"
)

type DatabaseError struct {
	Table string
	Code  int
}

func (e *DatabaseError) Error() string {
	return fmt.Sprintf("db error on table %s (code %d)", e.Table, e.Code)
}

func doWork() error {
	return fmt.Errorf("worker failed: %w", &DatabaseError{Table: "users", Code: 1045})
}

func main() {
	err := doWork()

	// INCORRECT: will panic at runtime
	// var target DatabaseError
	// if errors.As(err, &target) { ... }

	// CORRECT: target is *DatabaseError, pass &target (*DatabaseError*)
	var dbErr *DatabaseError
	if errors.As(err, &dbErr) {
		fmt.Printf("Matched: table=%s, code=%d\n", dbErr.Table, dbErr.Code)
	} else {
		fmt.Println("Did not match")
	}
}

If you declare var target DatabaseError and pass &target, the Go runtime panics immediately:

text
panic: errors: *target must be interface or implement error

It panics because *target is DatabaseError, which does not implement error. Only *DatabaseError does. To let errors.As populate the pointer variable, you allocate a nil pointer var dbErr *DatabaseError and pass its address &dbErr.

Gotcha 2: Custom Is methods bypassing reflection

When custom errors contain dynamic context (like a timestamp or query trace ID), two instances of the error are never equal via simple struct equality.

go
type APIError struct {
	StatusCode int
	TraceID    string
}

func (e *APIError) Error() string {
	return fmt.Sprintf("status %d (trace: %s)", e.StatusCode, e.TraceID)
}

var ErrUnauthorized = &APIError{StatusCode: 401}

Checking errors.Is(err, ErrUnauthorized) fails if err was created with a specific TraceID, because standard pointer equality fails and struct field comparison fails on mismatched TraceID strings.

Implement a custom Is(target error) bool method on your error struct. errors.Is looks for this method before falling back to equality checks:

go
package main

import (
	"errors"
	"fmt"
)

type APIError struct {
	StatusCode int
	TraceID    string
}

func (e *APIError) Error() string {
	return fmt.Sprintf("status %d (trace: %s)", e.StatusCode, e.TraceID)
}

func (e *APIError) Is(target error) bool {
	t, ok := target.(*APIError)
	if !ok {
		return false
	}
	// Match purely on status code, ignore trace ID variations
	return e.StatusCode == t.StatusCode
}

var ErrUnauthorized = &APIError{StatusCode: 401}

func fetchRecord() error {
	return fmt.Errorf("fetch: %w", &APIError{StatusCode: 401, TraceID: "req-xyz-987"})
}

func main() {
	err := fetchRecord()

	if errors.Is(err, ErrUnauthorized) {
		fmt.Println("Handled: request was unauthorized")
	} else {
		fmt.Println("Failed to match error")
	}
}

Run this:

text
Handled: request was unauthorized

Verifying fixes with unit tests

To verify your code handles interface typing and unwrapping without silent nil bugs, write unit tests that check both nil interface assignment and wrapped matching.

go
package main

import (
	"errors"
	"fmt"
	"testing"
)

func TestExecuteReturnsTrueNil(t *testing.T) {
	err := execute()
	if err != nil {
		t.Fatalf("expected nil error, got non-nil interface: %v", err)
	}
}

func TestWrappedDatabaseErrorMatches(t *testing.T) {
	orig := &DatabaseError{Table: "orders", Code: 500}
	wrapped := fmt.Errorf("service layer: %w", orig)

	var extracted *DatabaseError
	if !errors.As(wrapped, &extracted) {
		t.Fatalf("errors.As failed to extract *DatabaseError from wrapped chain")
	}

	if extracted.Table != "orders" {
		t.Errorf("expected table 'orders', got '%s'", extracted.Table)
	}
}

Run tests with race detection to verify memory safety across boundaries:

bash
go test -v -race ./...

If any function returns a concrete nil pointer inside an error interface, TestExecuteReturnsTrueNil fails with a clear message showing the non-nil interface pointing to <nil>, stopping the bug before it hits production.

More in Go