简体   繁体   中英

Why int32(0) is not reflect.DeepEqual to type Zero in Golang?

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

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 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM