英文:
Why int32(0) is not reflect.DeepEqual to type Zero in Golang?
问题
我在go-swagger包中找到了这种验证方式。
// Required validates an interface for requiredness
func Required(path, in string, data interface{}) *errors.Validation {
    val := reflect.ValueOf(data)
    if reflect.DeepEqual(reflect.Zero(val.Type()), val) {
        return errors.Required(path, in)
    }
    return nil
}
我尝试使用它,但它对我产生了一些疑问。
为什么下面的语句不是一个正确的陈述?
exper := int32(0)
reflect.DeepEqual(
   reflect.Zero(reflect.ValueOf(exper).Type()), 
   reflect.ValueOf(exper)
)
英文:
I found this sort of validation in go-swagger package.
// Required validates an interface for requiredness
func Required(path, in string, data interface{}) *errors.Validation {
	val := reflect.ValueOf(data)
	if reflect.DeepEqual(reflect.Zero(val.Type()), val) {
		return errors.Required(path, in)
	}
	return nil
}
I tried to use it and it forced me for some thoughts.
Why the following is not a true statement?
exper := int32(0)
reflect.DeepEqual(
   reflect.Zero(reflect.ValueOf(exper).Type()), 
   reflect.ValueOf(exper)
)
答案1
得分: 5
请查看reflect.Value的Godoc文档:
> 在两个Value上使用==运算符不会比较它们所表示的底层值,而是比较Value结构体的内容。要比较两个Value,请比较Interface方法的结果。
package main
import "reflect"
func main() {
    //var i int32
    exper := int32(0)
    r := reflect.DeepEqual(
        reflect.Zero(reflect.ValueOf(exper).Type()).Interface(),
        reflect.ValueOf(exper).Interface(),
    )
    println(r)  // true 
}
英文:
Please check the godocs of reflect.Value:
> Using == on two Values does not compare the underlying values they
> represent, but rather the contents of the Value structs. To compare
> two Values, compare the results of the Interface method.
package main
import "reflect"
func main() {
  //var i int32
  exper := int32(0)
  r := reflect.DeepEqual(
    reflect.Zero(reflect.ValueOf(exper).Type()).Interface(),
    reflect.ValueOf(exper).Interface(),
  )
  println(r)  // true 
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论