Other ways of verifying reflect.Type for int and float64

后端 未结 2 698
梦如初夏
梦如初夏 2021-02-11 03:00

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

2条回答
  •  感动是毒
    2021-02-11 03:46

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

提交回复
热议问题