14

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.

icza
  • 389,944
  • 63
  • 907
  • 827
manikanta p.s
  • 161
  • 1
  • 1
  • 4
  • 3
    Related question, please read answers there: [Hiding nil values, understanding why golang fails here](http://stackoverflow.com/questions/29138591/hiding-nil-values-understanding-why-golang-fails-here) – icza Jun 28 '16 at 08:08
  • 1
    Normaly you should try to avoid to use the reflect package. Why do you want to check if the interface is nil? Maybe the usage of an interface is not optimal and you shuold use an implementation of your interface. – apxp Jun 28 '16 at 09:42

2 Answers2

19

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() {
}
thanhpk
  • 3,900
  • 4
  • 29
  • 36
8

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.

Yash Srivastava
  • 850
  • 2
  • 9
  • 15