问题
Because not all types are comparable, e.g. a slice. So we can't do this
var v ArbitraryType
v == reflect.Zero(reflect.TypeOf(v)).Interface()
Edit - Solution reflect.DeepEqual
var v ArbitratyType
zero := reflect.Zero(reflect.TypeOf(v)).Interface()
isZero := reflect.DeepEqual(v, zero)
Go documentation about reflect.DeepEqual
DeepEqual tests for deep equality. It uses normal == equality where possible but will scan elements of arrays, slices, maps, and fields of structs.
回答1:
See this post:
Golang: Reflection - How to get zero value of a field type
Basically you need to have special cases for the non comparable types.
回答2:
As Peter Noyes points out, you just need to make sure you're not comparing a type which isn't comparable. Luckily, this is very straightforward 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 an example use here.
回答3:
Both of the following give me reasonable results (probably because they're the same?)
reflect.ValueOf(v) == reflect.Zero(reflect.TypeOf(v)))
reflect.DeepEqual(reflect.ValueOf(v), reflect.Zero(reflect.TypeOf(v)))
e.g. various integer 0 flavours and uninitialized struct
s are "zero"
Sadly, empty strings and arrays are not. and nil
gives an exception.
You could special case these if you wanted.
来源:https://stackoverflow.com/questions/33115946/how-to-know-if-a-variable-of-arbitrary-type-is-zero-in-golang