Skip to content

Instantly share code, notes, and snippets.

@mangatmodi
Last active November 3, 2023 18:40
Show Gist options
  • Save mangatmodi/06946f937cbff24788fa1d9f94b6b138 to your computer and use it in GitHub Desktop.
Save mangatmodi/06946f937cbff24788fa1d9f94b6b138 to your computer and use it in GitHub Desktop.
nil_check_working.go
package main
import (
"fmt"
"reflect"
)
type Animal interface {
MakeSound() string
}
type Dog struct{}
func (d *Dog) MakeSound() string {
return "Bark"
}
type Cat struct{}
func (c Cat) MakeSound() string {
return "Meow"
}
func isNil(i interface{}) bool {
return i == nil || reflect.ValueOf(i).IsNil()
}
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
}
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
}
func main() {
var d *Dog = nil
var a Animal = d
fmt.Println(isNilFixed(a))
var c Cat
a = c
fmt.Println(isNilFixed(a))
var m map[string] string
fmt.Println(isNilFixed(m))
var s []string
fmt.Println(isNilFixed(s))
var ch chan string
fmt.Println(isNilFixed(ch))
}
@dibikhin
Copy link

👍

@rms1000watt
Copy link

Thank you!

@antocap
Copy link

antocap commented Dec 19, 2021

Thank you very much for your gist and for your post

Here below you can find my two cents

func myIsNil(i Animal) bool {
	var ret bool
	switch i.(type) {
	case *Dog:
		v := i.(*Dog)
		ret = v == nil
	case Cat:
		ret = false
        default:
                 ret = isNilFixed(i)  // so isNilFixed() is called only if we forgot to implement some cases
                 // add some log to remember to add new cases to the switch to improve performance
	}
	return ret
}

Ciao,
Antonio

@bruno-anjos
Copy link

bruno-anjos commented Sep 2, 2022

Thanks for the gist, but I found something weird in it and double-checked in the playground and the code isNilFixed would actually panic in the Array case, because arrays can not be nil. Can you confirm?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment