3 回答

TA貢獻1804條經驗 獲得超8個贊
如果我理解正確,您想將數據解組為兩種類型的切片:
type A struct {
Foo string `json:"foo"`
ID string `json:"id"`
}
type B struct {
Bar string `json:"bar"`
Baz string `json:"baz"`
Eee string `json:"eee"`
}
來自SearchHit Source。
JSON 包可以為您完成大部分工作:
func executeQuery(q Query, v interface{}) error {
// Get a SearchHit. I am making this up.
// I have no idea how the package works.
searchHit, err := getHit(q)
if err != nil {
return err
}
// This is the important part. Convert the raw message to
// a slice of bytes and decode to the caller's slice.
return json.Unmarshal([]byte(*searchHit.Source), v)
}
您可以調用此函數以解碼為類型切片或指向類型的指針切片。
// Slice of type
var s1 []TypeA
if err := executeQuery(q1, &s1); err != nil {
// handle error
}
// Slice of pointer to type
var s2 []*TypeB
if err := error(q2, &s2); err != nil {
// handle error
}
我知道這不是問題的直接答案,但這就是通常處理這種情況的方式。
- 3 回答
- 0 關注
- 334 瀏覽
添加回答
舉報