我有 2 個專案,collections由accounts2 個結構表示,我想合并到一個回應中。
collections, accounts, err := h.Service.Many(ctx, params)
集合結構定義如下:
type Collection struct {
ID int64 `json:"id"`
Name *string `json:"name"`
Description *string `json:"description"`
Total *int64 `json:"total"`
}
并且帳戶被定義為這樣的地圖,accounts := make(map[int64][]string)資料看起來像這樣map[1:[19565 21423] 7:[]]
我想做的是合并這兩個,如下所示:
// merge into single struct
type CollectionWithAccounts struct {
Collections []*collection.Collection
AccountIDs []string
}
// initialize struct
collectionsWithAccounts := make([]CollectionWithAccounts, 0)
// merge strucst in loop
for _, collection := range collections {
for _, account := range accounts {
collectionsWithAccounts.Collections = append(collectionsWithAccounts, collection)
collectionsWithAccounts.Accounts = append(collectionsWithAccounts, account)
}
}
我怎樣才能完成這個合并?
uj5u.com熱心網友回復:
即使沒有任何回圈,您也可以這樣做:
package main
import "fmt"
type Collection struct {
ID int64 `json:"id"`
Name *string `json:"name"`
Description *string `json:"description"`
Total *int64 `json:"total"`
}
type AccountID map[int64][]string
// merge into single struct
type CollectionWithAccounts struct {
Collections []*Collection
AccountIDs []AccountID
}
func main() {
// get the data
// []*Collections, []AccountID, err
collections, accounts, err := h.Service.Many(ctx, params)
// handle error
if err != nil {
fmt.Println(err.Error())
// more logic
}
collectionsWithAccounts := CollectionWithAccounts{
Collections: collections,
AccountIDs: accounts,
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/457417.html
標籤:走
上一篇:在Golang中,只有case子句(沒有case運算式)和defaultcase的select陳述句有什么作用?
