普通网友 2016-07-15 06:45
浏览 206
已采纳

验证reflect.Type的其他方法int和float64

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
}

Is there more elegant solution instead of using 0 or 0.0 to get reflect.Type?

  • 写回答

2条回答 默认 最新

  • dtr87341 2016-07-15 06:49
    关注

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

    You can also use it in a switch:

    switch myType.Kind() {
    case reflect.Int:
        fmt.Println("int")
    case reflect.Float64:
        fmt.Println("float64")
    default:
        fmt.Println("Some other type")
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿