I have a int
/string
/bool
/etc.. value stored in an interface{}
and want to determine if it's uninitialized, meaning that it has a value of either
0
""
false
nil
How do I check this?
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.
Every type in golang, including user-defined type, itself has the information about type name, fields name and the function name. Golang reflection just reads these information or call the function. Through some mechanism, Golang can get the type name, storage size and so on.
The reflect. ValueOf() Function in Golang is used to get the new Value initialized to the concrete value stored in the interface i. To access this function, one needs to imports the reflect package in the program.
From what I understand, you want something like:
func IsZeroOfUnderlyingType(x interface{}) bool { return x == reflect.Zero(reflect.TypeOf(x)).Interface() }
When talking about interfaces and nil
, people always get confused with two very different and unrelated things:
nil
interface value, which is an interface value that doesn't have an underlying value. This is the zero value of an interface type.nil
interface value (i.e. it has an underlying value), but its underlying value is the zero value of its underlying type. e.g. the underlying value is a nil
map, nil
pointer, or 0 number, etc.It is my understanding that you are asking about the second thing.
Update: Due to the above code using ==
, it won't work for types that are not comparable. I believe that using reflect.DeepEqual()
instead will make it work for all types:
func IsZeroOfUnderlyingType(x interface{}) bool { return reflect.DeepEqual(x, reflect.Zero(reflect.TypeOf(x)).Interface()) }
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