2018-03-30 06:50
浏览 3.0k

在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{}

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, 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

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; 对于普通数据,接口大多数只能是数字,但必须是字符串类型,例如:

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

,然后所有数据将存储到 struct

  type someStruct struct {
 Number1 int 
 Number2 int 
 Number3 int 
 Number4 int 

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

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

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

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


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题