I have two interface{}
s a
and b
from JSON decoding and user input, let's say:
var a interface{} = ...
var b interface{} = ...
I know they are numbers. They could be any of the following types:
unit
unit8
uint16
uint32
uint64
int
int8
int16
int32
int64
float
float32
float64
I wrote some test code as follows. It turned out that when a variable is int
, it will fail with int64
assertion.
var a interface{} = 1
v, f := a.(int64)
fmt.Println(v, f) //0 false
v1, f1 := a.(int)
fmt.Println(v1, f1) //1 true
So now my question is as follows: in order to compare these two numbers, do I have to test all the permutations of these more than 10 types just in order to get the types of these two interface{}
variables? Ideally, I just want to cast them to int64
or float64
, but if they are int
or float
, I have no way to find them until exhausted all possible types.
If your input comes from JSON input, then it's a float64
, as per the doc:
To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:
- bool, for JSON booleans
- float64, for JSON numbers
- string, for JSON strings
- []interface{}, for JSON arrays
- map[string]interface{}, for JSON objects
- nil for JSON null
If its comes from user input, it is whatever you decided it was when you read it, so you shouldn't have any problem to get the right type.