reflection - 为什么 int32(0) 不是 reflect.DeepEqual 在 Golang 中键入零?

标签 reflection go swagger

我在 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)
)

最佳答案

请检查godocs 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 
}

关于reflection - 为什么 int32(0) 不是 reflect.DeepEqual 在 Golang 中键入零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36328236/

相关文章:

swagger - 如何在Wildfly内的Swagger 3.0中定义basePath

java - 静态变量的多个实例

c# - 如何从根 url 重定向到/swagger/ui/index?

c# - 如何使用反射调用泛型方法?

go - 如何完全禁用 HTTP/1.x 支持

go - golang中将byte[]转换为字符串奇怪占用堆

go - golang程序退出后如何保持子进程运行?

当我想使用 get_serializer_class() 根据 url 参数为不同的用户返回不同的字段时,django-rest-swagger 不起作用

java - Java中如何使用不同的ClassLoader重新加载已加载的类?

函数内的javascript函数