为什么在Golang中,int32(0)不等于类型Zero的reflect.DeepEqual?

huangapple go评论88阅读模式
英文:

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.ValueGodoc文档

> 在两个Value上使用==运算符不会比较它们所表示的底层值,而是比较Value结构体的内容。要比较两个Value,请比较Interface方法的结果。

Play链接

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.

Play

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 
}

huangapple
  • 本文由 发表于 2016年3月31日 16:38:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/36328236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定