Golang: An interface holding a nil value is not nil

Gary Lu
2 min readMay 21, 2019
  • Migrated to personal blog: link
  • Visit pacebits.com to check out recent projects I’m working on

Let’s start directly with an example (go playground):

package mainimport "fmt"func main() {    var a interface{}
fmt.Printf("a == nil is %t\n", a == nil)
var b interface{}
var p *int = nil
b = p
fmt.Printf("b == nil is %t\n", b == nil)

What is your expectation for the output? It will end up like:

a == nil is true
b == nil is false

It is somehow counter-intuitive at first glance, but it makes a lot more sense if we explore a little bit about the reflection model in Golang.

Under the hood, an interface in Golang consists of two elements: type and value. When we assign a nil integer pointer to an interface in our example above, the interface becomes (*int)(nil), and it is not nil. An interface equals nil only if both the type and value are nil.

Here is another example of this (go playground), which is a bad pattern to return the error:

package mainimport "fmt"func main() {
err :=…