Golang比较数字

huangapple go评论77阅读模式
英文:

Golang compare numbers

问题

我有两个interface{}变量ab,它们是从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{}变量的类型?理想情况下,我只想将它们转换为int64float64,但如果它们是intfloat,我无法找到它们,除非穷举所有可能的类型。

英文:

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.

huangapple
  • 本文由 发表于 2015年12月31日 18:32:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/34545019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定