Go: Check Nil interface the right way

  1. Type is null-able(like map, pointer etc) and value is nil
  2. Type itself is nil (of course value will be nil)
func isNil(i interface{}) bool {                        
return i == nil || reflect.ValueOf(i).IsNil() }
type Animal interface {
MakeSound() string
}
type Dog struct{}

func (d *Dog) MakeSound() string {
return "Bark"
}
func main() {
var d *Dog = nil
var a Animal = d
fmt.Println(isNil(a))
}
type Cat struct{}

func (c Cat) MakeSound() string {
return "Meow"
}
func main() {
var c Cat
var a Animal = c
fmt.Println(isNil(a))
}
panic: reflect: call of reflect.Value.IsNil on struct Value
  1. I would like to fail gracefully.
  2. Or It shall not fail. If a function accepts an argument at compile time, it should be ready to give correct result for that argument(and not fail). This makes things more predictable.

Better Version

So I ended up writing following version

func isNilFixed(i interface{}) bool {
if i == nil {
return true
}
switch reflect.TypeOf(i).Kind() {
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice:
return reflect.ValueOf(i).IsNil()
}
return false
}

Best Solution

However the best solution for our example would be to have following

func isNilBetter(i Animal) bool {
var ret bool
switch i.(type) {
case *Dog:
v := i.(*Dog)
ret = v == nil
case Cat:
ret = false
}
return ret
}
  1. We might have dozens of implementations of an interface.
  2. We might have accidentally implemented an interface (duck-typing), so we miss checks for that(I miss exhaustiveness of switch in Kotlin)
  3. We simply don’t know which interface we are going to use.

--

--

mangatmodi.com | High scalable services, Low latency coding, and Concurrency! Get’s excited by any tough problem.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mangat Rai Modi

Mangat Rai Modi

88 Followers

mangatmodi.com | High scalable services, Low latency coding, and Concurrency! Get’s excited by any tough problem.