我需要一个通用函数来检查某物是否等于它的零值。
从这里question ,我能够找到一个适用于值类型的函数。我修改它以支持指针:
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())
}
关于go - 如何使用 reflect.DeepEqual() 将指针的值与其类型的零值进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41756279/