在Struct中初始化嵌套映射

时间:2018-04-03 19:48:16

标签: dictionary go struct nested

我是Go的新手,我从REST端点消耗了一些数据。我已经解组了我的json,我正在尝试使用几个嵌套的地图填充自定义结构:

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

当我迭代我的功能时,我试图将它们添加到结构中的功能图。

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

在这种情况下如何初始化功能图?我觉得在阳光下尝试了一切都没有成功。是否更好Go形式为Feature和Story创建独立的结构,而不是在主结构中匿名定义它们?

1 个答案:

答案 0 :(得分:3)

composite literal必须以要初始化的类型开头。现在,显然这对于​​匿名结构非常笨重,因为你要重复相同的结构定义,所以最好不要使用匿名类型:

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
}

这样你就可以:

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