1 回答

TA貢獻(xiàn)1829條經(jīng)驗 獲得超9個贊
我更愿意解碼成一個結(jié)構(gòu)并讓json/encoding處理正確類型的工作。
type Input struct {
Title,
Selection string
CostPerDayInCent int64
Description string
User int64
AllowMobileContact,
AllowEmailContact,
IsActive bool
}
由于幾個原因,這種方法非常普遍和有用。首先,您可以選擇類型。其次,您正在定義一個類型,因此您可以附加函數(shù),我發(fā)現(xiàn)它作為一種組織代碼并避免將結(jié)構(gòu)作為顯式函數(shù)參數(shù)傳遞的方法非常方便。第三,您可以將注釋附加到結(jié)構(gòu)的字段,進(jìn)一步調(diào)整解組。
最后,對我來說,最重要的是,您正在以 Go 處理數(shù)據(jù)的方式思考數(shù)據(jù)。在許多流行的現(xiàn)代語言(如 Python)中,代碼和文檔通常不會將類型附加到函數(shù),或嘗試顯式枚舉對象的屬性。圍棋不一樣。它消除了固有的語言反射是它如此高效的原因之一。這可以為程序員提供巨大的好處——當(dāng)您了解所有類型時,您就可以確切地知道事物的行為方式,并且可以準(zhǔn)確地確定必須傳遞您調(diào)用的函數(shù)的內(nèi)容。我建議您接受顯式類型,并盡可能避免將 json 解碼為面向接口的類型。你會知道你在處理什么,你也可以為你的消費者明確地定義它。
https://play.golang.org/p/egaequIT8ET與您的方法形成鮮明對比,您無需費心定義類型 - 但您也沒有機會選擇它們。
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type Input struct {
Title,
Selection string
CostPerDayInCent int64
Description string
User int64
AllowMobileContact,
AllowEmailContact,
IsActive bool
}
func main() {
var input = `{
"Title": "Example Title",
"Section": "machinery",
"CostPerDayInCent": 34500,
"Description": "A description",
"User": 4,
"AllowMobileContact": true,
"AllowEmailContact": true,
"IsActive": false
}`
// map[string]interface
data := make(map[string]interface{})
if err := json.NewDecoder(bytes.NewBufferString(input)).Decode(&data); err != nil {
panic(err)
}
fmt.Printf("%f %T\n", data["CostPerDayInCent"], data["CostPerDayInCent"])
// structure
obj := new(Input)
if err := json.NewDecoder(bytes.NewBufferString(input)).Decode(obj); err != nil {
panic(err)
}
fmt.Printf("%d %T", obj.CostPerDayInCent, obj.CostPerDayInCent)
}
- 1 回答
- 0 關(guān)注
- 157 瀏覽
添加回答
舉報