25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →
Nil Checking and Interface Nil Gotcha in Go
Code Snippet

Nil Checking and Interface Nil Gotcha in Go

go

Nil checking in Go is straightforward for pointers and simple types, but interfaces introduce a subtle gotcha. An interface value is only nil when both its type and value are nil. If you assign a nil *MyError pointer to an error interface variable, the interface itself is not nil because it now holds a type (*MyError) even though the underlying value is nil.

This gotcha catches many Go developers. In our example, myErr is a nil pointer of type *MyError. When we assign it to err (an error interface), the interface stores the type information alongside the nil value. The comparison err == nil returns false because the interface has a concrete type. Always be aware of this distinction when returning errors from functions to avoid unexpected behaviour.

Further Reading: