1

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?

1

1 Answer 1

3

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

To illustrate the unwieldiness of using an anonymous struct definition, here is an example play.golang.org/p/T-e3ajEUhiu

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.