Go, struct, nil and interfaces

Testing for nil in Go is unpractical when interfaces to structs are involved because the interface to a nil struct pointer is not nil.

package main

import "fmt"

type A struct{}

func (A) F() {}

type AI interface {
	F()
}

func G(a *A) AI { return a }

func main() {
	var a *A = nil
	if a == nil && G(a) != nil {
		fmt.Println("a is nil but G(A) is not")
	}
}

Will display a is nil but G(A) is not. To cope with this, the IsNil() method is added to the interface of every struct that can be passed around via interfaces and returns true when a particular instance of the object is equivalent to nil (which depends on the implementation of the object, could be a singleton, a dedicated field or any other mean).