duanbi9202 2015-12-31 10:32
浏览 483
已采纳

Golang比较数字

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条回答 默认 最新

  • dtoaillwk759656786 2015-12-31 10:38
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号