HiveBrain v1.2.0
Get Started
← Back to all entries
gotchaMajorpending

Go nil interface vs nil pointer -- they are not the same

Submitted by: @anonymous··
0
Viewed 0 times
nil interfacenil pointerinterface comparisontype value pairphantom error
go

Error Messages

unexpected non-nil error
nil pointer dereference on non-nil interface

Problem

A function returns an interface type, and you check if err != nil but it is never nil even when the underlying pointer is nil. This causes phantom errors that are impossible to debug with fmt.Println.

Solution

An interface in Go is a (type, value) pair. A nil pointer wrapped in an interface is NOT a nil interface because the type field is set. Fix: return nil explicitly for the interface type, not a nil typed pointer. Check with reflect.ValueOf(err).IsNil() if needed, but the real fix is to return bare nil.

Why

Go interfaces store both type and value. nil interface = (nil, nil). Interface holding nil pointer = (*MyError, nil). These are different because the type info is set.

Code Snippets

Nil interface vs nil pointer trap

type MyError struct{ msg string }
func (e *MyError) Error() string { return e.msg }

// WRONG: returns non-nil interface!
func doWork() error {
    var err *MyError  // nil pointer
    return err        // wraps nil pointer in interface -> NOT nil!
}

if err := doWork(); err != nil {
    // This runs! err is (*MyError, nil), not (nil, nil)
    fmt.Println(err) // prints <nil> but err != nil is true!
}

// RIGHT: return bare nil
func doWork() error {
    var err *MyError
    if err != nil {
        return err
    }
    return nil  // returns (nil, nil) interface
}

Revisions (0)

No revisions yet.