I need a generic function to check whether something is equal to its zero-value or not.
From this question, I was able to find a function that worked with value types. I modified it to support pointers:
func isZeroOfUnderlyingType(x interface{}) bool {
rawType := reflect.TypeOf(x)
//source is a pointer, convert to its value
if rawType.Kind() == reflect.Ptr {
rawType = rawType.Elem()
}
return reflect.DeepEqual(x, reflect.Zero(rawType).Interface())
}
Unfotunately, this didn't work for me when doing something like this:
type myStruct struct{}
isZeroOfUnderlyingType(myStruct{}) //Returns true (works)
isZeroOfUnderlyingType(&myStruct{}) //Returns false (doesn't) work
This is because &myStruct{}
is a pointer and there is no way to dereference an interface{}
inside the function. How do I compare the value of that pointer against the zero-value of its type?
reflect.Zero()
returns a reflect.Value
. reflect.New()
returns a pointer to a zero value.
I updated the function to check the case where x
is a pointer to something:
func isZeroOfUnderlyingType(x interface{}) bool {
rawType := reflect.TypeOf(x)
if rawType.Kind() == reflect.Ptr {
rawType = rawType.Elem()
return reflect.DeepEqual(x, reflect.New(rawType).Interface())
}
return reflect.DeepEqual(x, reflect.Zero(rawType).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