Currently I'm using this helper function to check for nil and nil interfaces
func isNil(a interface{}) bool { defer func() { recover() }() return a == nil || reflect.ValueOf(a).IsNil() }
Since reflect.ValueOf(a).IsNil()
panics if the value's Kind is anything other than Chan
, Func
, Map
, Ptr
, Interface
or Slice
, I threw in the deferred recover()
to catch those.
Is there a better way to achieve this check? It think there should be a more straight forward way to do this.
There are two things: If y is the nil interface itself (in which case y==nil will be true), or if y is a non-nil interface but underlying value is a nil value (in which case y==nil will be false).
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.
nil is a frequently used and important predeclared identifier in Go. It is the literal representation of zero values of many kinds of types. Many new Go programmers with experiences of some other popular languages may view nil as the counterpart of null (or NULL ) in other languages.
In the Go programming language, nil is a zero value. Recall from unit 2 that an integer declared without a value will default to 0. An empty string is the zero value for strings, and so on. A pointer with nowhere to point has the value nil . And the nil identifier is the zero value for slices, maps, and interfaces too.
See for example Kyle's answer in this thread at the golang-nuts mailing list.
In short: If you never store (*T)(nil)
in an interface, then you can reliably use comparison against nil, no need to use reflection. On the other hand, assigning untyped nil to an interface is always OK.
If neither of the earlier options works for you, the best I could came up so far is:
if c == nil || (reflect.ValueOf(c).Kind() == reflect.Ptr && reflect.ValueOf(c).IsNil())
At least it detects (*T)(nil) cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With