The generics proposal has a section on how to return the zero value of a parameterized type, but it does not mention how to check if a value of a parameterized type is the zero value. The only way I can think of is to use reflect.ValueOf(...).IsZero(), is there an alternative?
CodePudding user response:
If the type is comparable, then compare the value to a variable set to the zero value of the type.
var zero T
isZero := v == zero
Use the reflect package if the type is not comparable:
isZero := reflect.ValueOf(&v).Elem().IsZero()
CodePudding user response:
Use the equal operator with the *new(T)
idiom. The constraint of the generic param must be, or embed,comparable
to support the equality operator, or specify a type set of comparable types:
func IsZero[T comparable](v T) bool {
return v == *new(T)
}
If you can’t constrain T
to comparable
then you’re left with reflection. Zombo’s suggestion to address the variable like this:
is superior to simply reflect.ValueOf(v).IsZero()
because ValueOf
takes an interface{}
argument and if v
just happens to be an interface{}
you would loose that information. I don’t think that with generics you will often instantiate a function with interface{}
but it’s worth knowing.