Reputation: 171
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.
Upvotes: 15
Views: 27526
Reputation: 4297
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() {
}
Upvotes: 22
Reputation: 992
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).
Here's an example.
Upvotes: 8