Last active
November 3, 2023 18:40
-
-
Save mangatmodi/06946f937cbff24788fa1d9f94b6b138 to your computer and use it in GitHub Desktop.
nil_check_working.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
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
Thank you very much for your gist and for your post
Here below you can find my two cents
Ciao,
Antonio