douya7309
2018-03-30 06:50
浏览 3.1k
已采纳

在Golang中将interface {}直接转换为int,其中interface将数字存储为字符串

I got a map[string]interface{} because decoding to JSON; with normal data, interface most be only a number but in type string, like this :

var a interface{}
a="3"

And then all data will be stored into a struct.

type someStruct struct {
   ID string
   Number1 int
   Number2 int
   Number3 int
   Number4 int
}

So I need to convert interface to int, but can´t do it easily and efficiently because only the code would be https://play.golang.org/p/oktbvTUbk93, pretty annoying and code does not seem to be readable if you take in mind the fact that I should handle all of possible errors

I would want to convert it directly to int, I´ve been searching for solutions but any of this convertions works as I want https://play.golang.org/p/Dw67U6kZwHC

In case you wondering why I don´t just decode it into struct directly, it´s because it´s dynamic data, the actual decoding occurs like this :

type dataIn struct {
   Code int         `json:"code"`
   ID   string      `json:"id"`
   Data interface{} `json:"data"`
}

And then I handle Data according to code and id, and they all are different data structures, so I can´t directly handle it with JSON

图片转代码服务由CSDN问答提供 功能建议

我得到了一个map [string] interface {},因为它可以解码为JSON; 对于普通数据,接口大多数只能是数字,但必须是字符串类型,例如:</ p>

  var a interface {} 
a =“ 3” 
 </ code> <  / pre> 
 
 

,然后所有数据将存储到 struct </ strong>。</ p>

  type someStruct struct {
 ID字符串 
 Number1 int 
 Number2 int 
 Number3 int 
 Number4 int 
} 
 </ code> </ pre> 
 
 

所以我需要将接口转换为int,但是不能 它很容易且有效,因为只有代码会是 https://play.golang.org/p/oktbvTUbk93 < / a>,很烦人,如果您考虑到我应该处理所有可能的错误的事实,代码似乎也不可读</ p>

我想将其直接转换为int, 我一直在寻找解决方案,但任何这种转换都可以按我的要求运行 https://play.golang。 org / p / Dw67U6kZwHC </ p>

如果您想知道为什么我不这样做 不仅将其直接解码为struct,还因为它是动态数据,实际的解码是这样的:</ p>

  type dataIn struct {
 Code int`json  :“ code”`
 ID字符串`json:“ id”`
数据接口{}`json:“ data”`
} 
 </ code> </ pre> 
 
 

然后我根据代码和ID处理数据,它们都是不同的数据结构,因此我无法直接使用JSON处理</ p> </ div>

3条回答 默认 最新

相关推荐 更多相似问题