Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick way to detect empty values via reflection in Go

Tags:

reflection

go

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
  • or nil

How do I check this?

like image 467
Era Avatar asked Dec 16 '12 13:12

Era


People also ask

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.

How does Golang reflection work?

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.

What is reflect value Golang?

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.


1 Answers

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:

  1. A nil interface value, which is an interface value that doesn't have an underlying value. This is the zero value of an interface type.
  2. A non-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()) } 
like image 111
newacct Avatar answered Oct 04 '22 16:10

newacct