英文:
Golang compare numbers
问题
我有两个interface{}
变量a
和b
,它们是从JSON解码和用户输入中得到的。假设如下:
var a interface{} = ...
var b interface{} = ...
我知道它们是数字。它们可能是以下任意一种类型:
unit
unit8
uint16
uint32
uint64
int
int8
int16
int32
int64
float
float32
float64
我编写了一些测试代码,结果发现当变量是int
类型时,使用int64
断言会失败。
var a interface{} = 1
v, f := a.(int64)
fmt.Println(v, f) //0 false
v1, f1 := a.(int)
fmt.Println(v1, f1) //1 true
所以现在我的问题是:为了比较这两个数字,我是否必须测试这超过10种类型的所有排列,以获取这两个interface{}
变量的类型?理想情况下,我只想将它们转换为int64
或float64
,但如果它们是int
或float
,我无法找到它们,除非穷举所有可能的类型。
英文:
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.
答案1
得分: 8
如果您的输入来自JSON输入,那么根据文档,它是一个float64
类型:
为了将JSON解组为接口值,Unmarshal将以下类型之一存储在接口值中:
- bool,用于JSON布尔值
- float64,用于JSON数字
- string,用于JSON字符串
- []interface{},用于JSON数组
- map[string]interface{},用于JSON对象
- nil,用于JSON null
如果它来自用户输入,那么在读取时它是您决定的类型,所以您不应该遇到任何获取正确类型的问题。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论