Check if interface value is nil in Go without using reflect

17,677

Solution 1

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() {
}

Solution 2

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.

Share:
17,677
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    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.