How to find out if a variable is of arbitrary type Zero in Golang?

Because not all types are comparable, for example. slice. Therefore we cannot do this

var v ArbitraryType v == reflect.Zero(reflect.TypeOf(v)).Interface() 

Change - The solution reflects .DeepEqual

 var v ArbitratyType zero := reflect.Zero(reflect.TypeOf(v)).Interface() isZero := reflect.DeepEqual(v, zero) 

Go to the documentation for reflect.DeepEqual

DeepEqual tests for deep equality. If possible, it uses the expression normal ==, but will check the elements of arrays, slices, maps, and structure fields.

+5
source share
3 answers

See this post:

Golang: Reflection - How to get a null field type value

Basically, you need special cases for disparate types.

+2
source

As Peter Noyes points out, you just need to make sure that you are not comparing a type that is not comparable. Fortunately, this is very simple with the reflect package:

 func IsZero(v interface{}) (bool, error) { t := reflect.TypeOf(v) if !t.Comparable() { return false, fmt.Errorf("type is not comparable: %v", t) } return v == reflect.Zero(t).Interface(), nil } 

See usage example here .

+2
source

Both of the ones below give me reasonable results (probably because they are the same?)

 reflect.ValueOf(v) == reflect.Zero(reflect.TypeOf(v))) reflect.DeepEqual(reflect.ValueOf(v), reflect.Zero(reflect.TypeOf(v))) 

eg. various integer 0 flavors and uninitialized struct are "zero"

Unfortunately, empty strings and arrays are not. and nil gives an exception.
If you would like, you could take advantage of a special occasion.

+2
source

Source: https://habr.com/ru/post/1233672/


All Articles