Merging of map and struct golang

Issue

I have 2 items, collections and accounts represented by 2 structs that I would like to merge into a single response.

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

The collection struct is defined as follows:

type Collection struct {
    ID          int64      `json:"id"`
    Name        *string    `json:"name"`
    Description *string    `json:"description"`
    Total       *int64     `json:"total"`
}

And accounts is defined as a map as such accounts := make(map[int64][]string) and the data looks like this map[1:[19565 21423] 7:[]]

What I would like to do is merge these 2 something like the following:

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

How can I accomplish this merge?

Solution

You can do this even without any loops:

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

Answered By – ABDULLOKH MUKHAMMADJONOV

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.