feik
feik

Reputation: 387

Initializing Nested Maps in Struct

I am relatively new to Go and I am consuming some data from a REST endpoint. I have unmarshaled my json and I am trying to populate a custom struct with a couple of nested maps:

type EpicFeatureStory struct {
    Key         string
    Description string
    Features    map[string]struct {
        Name        string
        Description string
        Stories     map[string]struct {
            Name        string
            Description string
        }
    }
}

As I iterate over my features I am trying to add them to the Features map within the struct.

// One of my last attempts (of many)
EpicData.Features = make(EpicFeatureStory.Features)

for _, issue := range epicFeatures.Issues {
        issueKey := issue.Key
        issueDesc := issue.Fields.Summary

        EpicData.Features[issueKey] = {Name: issueKey, Description: issueDesc}
        fmt.Println(issueKey)
}

How does one initialize the Features map in this case? I feel like have tried everything under the sun without success. Is it better Go form to create independent structs for Feature and Story rather than anonymously defining them within the main struct?

Upvotes: 1

Views: 2300

Answers (1)

Adrian
Adrian

Reputation: 46592

A composite literal must start with the type being initialized. Now, obviously that's pretty unwieldy with anonymous structs because you'd be repeating the same struct definition, so it would probably be better not to use an anonymous type:

type Feature struct {
    Name        string
    Description string
    Stories     map[string]Story 
}

type Story struct {
    Name        string
    Description string
}

type EpicFeatureStory struct {
    Key         string
    Description string
    Features    map[string]Feature
}

So that you can just:

// You can only make() a type, not a field reference
EpicData.Features = make(map[string]Feature)

for _, issue := range epicFeatures.Issues {
        issueKey := issue.Key
        issueDesc := issue.Fields.Summary

        EpicData.Features[issueKey] = Feature{Name: issueKey, Description: issueDesc}
        fmt.Println(issueKey)
}

Upvotes: 3

Related Questions