The Biggest Interface Gotcha

Nil Interface vs Nil Pointer

A nil interface is not nil because it contains a type descriptor, while a nil pointer does not; check the underlying value to detect nil pointers inside interfaces.

A nil interface is not equal to a nil pointer because a nil interface contains a non-nil type descriptor, whereas a nil pointer has no type information attached to it. You must check the interface value itself or use a type assertion to distinguish them.

var ptr *int = nil
var iface interface{} = ptr

// This prints true because the interface holds a type (*int) and a value (nil)
fmt.Println(iface == nil) // false

// This prints true because the pointer itself is nil
fmt.Println(ptr == nil)   // true

// Correct way to check if the interface holds a nil pointer
if p, ok := iface.(*int); ok && p == nil {
    fmt.Println("Interface holds a nil *int")
}