I need to check if an interface value is `nil.
But by using reflection it is giving me an error:
reflect: call of reflect.Value.Bool on struct Value.
Through nil
it is not giving an error for nil
value.
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 predefined identifier in Go that represents zero values of many types. nil is usually mistaken as null (or NULL) in other languages, but they are different. Note: nil can be used without declaring it.
The reflect. IsNil() Function in Golang is used to check whether its argument v is nil. The argument must be a chan, func, interface, map, pointer, or slice value; if it is not, IsNil panics.
The interface type that specifies zero methods is known as the empty interface: interface{} An empty interface may hold values of any type. (Every type implements at least zero methods.) Empty interfaces are used by code that handles values of unknown type.
Interface is a pair of (type, value)
, when you compare a interface with nil, you are comparing the pair (type, value) with nil. To just compare interface value, you either have to convert it to a struct (through type assertion) or use reflection.
do a type assertion when you know the type of the interface
if i.(bool) == nil {
}
otherwise, if you don't know the underlying type of the interface, you may have to use reflection
if reflect.ValueOf(i).IsNil() {
}
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