gpt4 book ai didi

Golang 比较数字

转载 作者:IT王子 更新时间:2023-10-29 01:51:15 25 4
gpt4 key购买 nike

我有两个来自 JSON 解码和用户输入的接口(interface){} ab,比方说:

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,我在穷尽所有可能的类型之前无法找到它们。

最佳答案

如果您的输入来自 JSON 输入,那么它是一个 float64,根据 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

如果它来自用户输入,它就是您阅读时决定的任何内容,因此获得正确的类型应该没有任何问题。

关于Golang 比较数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34545019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com