Go's interfaces and nil by example
I've recently been involved in conversations with a few Go developers who have
expressed frustration about Go's interfaces with respect to nil. It seems not
everyone understands that interfaces are a reference type (like a pointer), and
they can reference other reference types (i.e., pointers, maps, slices, etc).
Because all reference types have a nil (zero) value, an interface can be nil
or an interface can reference a nil pointer; people may fail to realize that
the nility of the interface is independent from the nility of the thing it
points to, and when we ask (for example) if err != nil
, we're actually asking
is the interface nil?, not is the value behind the interface nil?. Here are
a few examples that will (hopefully) demonstrate this clearly: