英文:
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)
// 如果是指针,转换为其值
if rawType.Kind() == reflect.Ptr {
rawType = rawType.Elem()
}
return reflect.DeepEqual(x, reflect.Zero(rawType).Interface())
}
不幸的是,当我像这样做时,它对我不起作用:
type myStruct struct{}
isZeroOfUnderlyingType(myStruct{}) // 返回 true(有效)
isZeroOfUnderlyingType(&myStruct{}) // 返回 false(无效)
这是因为&myStruct{}
是一个指针,在函数内部无法解引用interface{}
。我该如何将该指针的值与其类型的零值进行比较?
英文:
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?
答案1
得分: 4
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())
}
英文:
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())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论