我發(fā)現(xiàn)自己經(jīng)常執(zhí)行以下操作,并希望減少重復(fù)。var customer model.Customerdecoder := json.NewDecoder(r.Body)decoder.DisallowUnknownFields()err := decoder.Decode(&customer)if err != nil { fmt.Print(err)}doSomethingWith(customer)我想寫一個(gè)簡(jiǎn)單的函數(shù),可以吸收和一些對(duì)象來(lái)映射到,即r.Bodymodel.Customer所以類似的東西(無(wú)效的golang)func fromJson(body io.ReadCloser, obj T) { var obj decoder := json.NewDecoder(body) decoder.DisallowUnknownFields() err := decoder.Decode(&obj) if err != nil { fmt.Print(err) } return obj;}
1 回答

DIEA
TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以使用 或 等待泛型:interface{}
func fromJson(body io.ReadCloser, obj interface{}) error { decoder := json.NewDecoder(body) decoder.DisallowUnknownFields() return decoder.Decode(obj) }
例如,如果您檢查文檔的Decode
,您可以看到它使用此機(jī)制,這在Go中很常見。
工作樣本:https://play.golang.org/p/D3GDKtUJxHC
- 1 回答
- 0 關(guān)注
- 135 瀏覽
添加回答
舉報(bào)
0/150
提交
取消