在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()
或Type.Kind()
方法,其可能的值在reflect
程序包中作为常量列出Kind
。
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
和reflect.Value
都有一个Kind()
方法,因此,如果您以reflect.ValueOf(myVar)
和开头,都可以使用它reflect.TypeOf(myVar)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句