在golang中,JSON消息中的数字总是被解析为float64。
为了检测它是否实际上是整数,我使用reflect.TypeOf()
检查其类型。
不幸的是没有常数代表reflect.Type
.
intType := reflect.TypeOf(0)
floatType := reflect.TypeOf(0.0)
myType := reflect.TypeOf(myVar)
if myType == intType {
// do something
}
有没有更优雅的解决方案而不是使用 0 或 0.0 来获取reflect.Type
?
您还可以使用Value.Kind() https://golang.org/pkg/reflect/#Value.Kind or Type.Kind() https://golang.org/pkg/reflect/#Type其可能值被列为常量的方法reflect
包,在文档中Kind https://golang.org/pkg/reflect/#Kind type.
myType := reflect.TypeOf(myVar)
if k := myType.Kind(); k == reflect.Int {
fmt.Println("It's of type int")
} else if k == reflect.Float64 {
fmt.Println("It's of type float64")
}
您还可以在switch
:
switch myType.Kind() {
case reflect.Int:
fmt.Println("int")
case reflect.Float64:
fmt.Println("float64")
default:
fmt.Println("Some other type")
}
请注意,两者reflect.Type https://golang.org/pkg/reflect/#Type and reflect.Value https://golang.org/pkg/reflect/#Value has a Kind()
方法,所以如果你开始的话你可以使用它reflect.ValueOf(myVar)
而且如果你从reflect.TypeOf(myVar)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)