The zero value for a Go interface is
nil. But unlike the
nil for concrete types (e.g: pointer, slice), checking for
nil interface is not as straightforward.
In this post, we’ll look at how we can check if an interface is
nil using the
First, check out the following code snippet:
The last line will always prints false, and go-staticcheck will give us a warning.
Under the hood, Go’s interfaces are a pair of pointers. One points to the underlying type and one points to the underlying value.
In this case, because we assign a value that’s concretely typed to
i, the interface is no longer
nil, even though the assigned value is
Or to word it a little differently, if a
nil variable with a concrete type is assigned to a variable with an interface type, the interface type is definitely not
An interface is only considered
nilwhen both its type and value are
To reliably check if the value associated with an interface is
nil, we need two use the
isNil methods from
IsValid check on line 3 returns
iv is not a
Next we check whether the value associated with the interface is
nil using the
IsNil method. Note that the
IsNil method can only be called on a type that can contain
nil, thence the case statement above it.
That’s how you can check for
nil interface in Go. Before we end this post, let’s see how the checker function does with our initial example.