[英]convert interface{} directly to int in Golang, where interface stores a number as string
我得到了一個map [string] interface {},因為它可以解碼為JSON; 對於普通數據,接口大多數只能是一個數字,但必須是字符串類型,例如:
var a interface{}
a="3"
然后所有數據將存儲到struct中 。
type someStruct struct {
ID string
Number1 int
Number2 int
Number3 int
Number4 int
}
因此,我需要將接口轉換為int,但不能輕松高效地完成,因為只有代碼會是https://play.golang.org/p/oktbvTUbk93 ,非常煩人,如果您看不到代碼,則似乎不可讀請記住我應該處理所有可能的錯誤的事實
我想將其直接轉換為int,我一直在尋找解決方案,但任何這種轉換都可以按我的要求工作https://play.golang.org/p/Dw67U6kZwHC
如果您想知道為什么我不直接將其解碼為struct,這是因為它是動態數據,所以實際的解碼是這樣的:
type dataIn struct {
Code int `json:"code"`
ID string `json:"id"`
Data interface{} `json:"data"`
}
然后我根據代碼和ID處理數據,它們都是不同的數據結構,因此我無法直接使用JSON處理數據
在一個地方創建一個幫您解析和驗證的幫助函數:
func parseInt(i interface{}) (int, error) {
s, ok := i.(string)
if !ok {
return 0, errors.New("not string")
}
return strconv.Atoi(s)
}
您可以在需要的地方使用它。 這是一個完整的示例,其中我還使用了另一個幫助程序功能,該功能負責錯誤處理:
m := map[string]interface{}{
"number1": "1",
"number2": "2",
"number3": "3",
"number4": "4",
"ID": "asdsa",
"Title": "asdas",
}
getInt := func(key string) int {
n, err := parseInt(m[key])
if err != nil {
panic(err) // Decide what you wanna do with error
}
return n
}
// converting to struct
data := element{
ID: m["ID"].(string),
Title: m["Title"].(string),
Number1: getInt("number1"),
Number2: getInt("number2"),
Number3: getInt("number3"),
Number4: getInt("number4"),
}
fmt.Printf("%+v\n", data)
上面的輸出(在Go Playground上嘗試):
{ID:asdsa Title:asdas Number1:1 Number2:2 Number3:3 Number4:4}
還要注意,開源軟件包github.com/icza/dyno
應該可以幫助您輕松處理動態對象。 (公開:我是作者。)例如,它具有dyno.GetInteger()
函數,該函數能夠從多種類型(例如整數,浮點數,字符串等)中提取int64
值。
聽起來您需要的是在主結構上的自定義解組json方法。 首先,解組到您的主要結構中以獲取代碼和ID,然后在switch語句中使用它們確定用於其余數據的結構,然后解組,在Data字段中攪動該結構。
我仍然沒有得到您所說的結構是動態生成的部分。 無論如何,您可以附加一個進行int轉換的struct方法。 如果類型為interface{}
的Data
字段總是保留整數,請嘗試以下操作:
type DataIn struct {
Code int `json:"code"`
ID string `json:"id"`
Data interface{} `json:"data"`
}
func (s DataIn) toInt() int {
switch t := s.Data.(type)
case int:
i, _ := strings.Atoi(fmt.Sprintf("%v",s.Data))
return i
}
// using it
sampleData := someStruct{
Number1: datain.toInt(),
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.