gpt4 book ai didi

go - map 和 struct golang 的合并

转载 作者:行者123 更新时间:2023-12-05 05:43:44 25 4
gpt4 key购买 nike

我有 2 个项目,collectionsaccounts 由 2 个结构表示,我想将它们合并到一个响应中。

集合、账户、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 被定义为这样的 map 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)
}
}

我怎样才能完成这个合并?

最佳答案

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

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

关于go - map 和 struct golang 的合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71756914/

25 4 0
文章推荐: javascript -