合并 map 和 struct 的方法(Golang)。

3

我有两个项目,collectionsaccounts,由两个结构体表示,我希望将它们合并为单个响应。

collections, accounts, err := h.Service.Many(ctx, params)

collection结构体的定义如下:

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)
    }
}

我该如何完成这个合并?
1个回答

1

即使没有任何循环,您也可以做到这一点:

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,
    }   
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接