I want convert interface value to number, but when interface is number or number string, it will not work, I do not know why we can't convert by this way?
package main
import (
"encoding/json"
"fmt"
"reflect"
)
func main() {
number := 10
strNumber := "10"
test(number)
test(strNumber)
}
func test(i interface{}) {
strNum, ok := i.(json.Number)
fmt.Println(strNum, ok, reflect.TypeOf(i))
}
It will produce result like this:
false int
false string
Here's your example in Go:
package main
import (
"encoding/json"
"fmt"
"strconv"
)
func main() {
number := 10
strNumber := "10"
test(number)
test(strNumber)
}
func test(i interface{}) {
var strNum string
switch x := i.(type) {
case int:
strNum = strconv.Itoa(x)
case string:
if _, err := strconv.ParseInt(x, 10, 64); err == nil {
strNum = x
}
}
jsonNum := json.Number(strNum)
fmt.Printf("%[1]v %[1]T
", jsonNum)
}
Playground: https://play.golang.org/p/iDSxrORX9yc
Output:
10 json.Number
10 json.Number