Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if interface value is nil in Go without using reflect

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.

like image 812
manikanta p.s Avatar asked Jun 28 '16 07:06

manikanta p.s


People also ask

Can an interface be nil Golang?

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.

Is nil null in Go?

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.

How do you know if reflection is nil?

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.

What is empty interface in Go?

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.


1 Answers

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() {
}
like image 118
thanhpk Avatar answered Sep 21 '22 13:09

thanhpk