[英]Why int32(0) is not reflect.DeepEqual to type Zero in Golang?
[英]How do I use reflect.DeepEqual() to compare a pointer's value against the zero value of its type?
我需要一个通用函数来检查某项是否等于其零值。
通过这个问题 ,我能够找到一个适用于值类型的函数。 我修改了它以支持指针:
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())
}
不幸的是,当执行以下操作时,这对我不起作用:
type myStruct struct{}
isZeroOfUnderlyingType(myStruct{}) //Returns true (works)
isZeroOfUnderlyingType(&myStruct{}) //Returns false (doesn't) work
这是因为&myStruct{}
是指针,并且无法在函数内部取消引用interface{}
。 如何将指针的值与其类型的零值进行比较?
reflect.Zero()
返回一个reflect.Value
。 reflect.New()
返回一个指向零值的指针。
我更新了该函数以检查x
是指向某物的指针的情况:
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())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.