我在 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.
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/