验证reflect.Type的其他方法int和float64 [英] Other ways of verifying reflect.Type for int and float64
问题描述
在golang中,始终将JSON消息中的数字解析为float64。
为了检测它是否实际上是整数,我使用了 reflect.TypeOf()
来检查其类型。
不幸的是,没有常量表示 reflect.Type
。
In golang, a number in JSON message is always parsed into float64.
In order to detect if it is actually integer, I am using reflect.TypeOf()
to check its type.
Unfortunately there is no constant that represents 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
?
Is there more elegant solution instead of using 0 or 0.0 to get reflect.Type
?
推荐答案
您也可以使用< a href = https://golang.org/pkg/reflect/#Value.Kind rel = noreferrer> Value.Kind()
或 Type.Kind()
方法可能的值在reflect 包中作为常量列出。 = noreferrer> 类型
。
You may also use the Value.Kind()
or Type.Kind()
method whose possible values are listed as constants in the reflect
package, at the doc of the 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 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)$ c开头,则可以使用它$ c>。
Note that both reflect.Type
and reflect.Value
has a Kind()
method, so you can use it if you start with reflect.ValueOf(myVar)
and also if you start with reflect.TypeOf(myVar)
.
这篇关于验证reflect.Type的其他方法int和float64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!