在结构中初始化嵌套地图



我相对较新,我正在从静止端点那里消费一些数据。我已经解雇了我的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)
}

在这种情况下,如何初始化功能映射?我觉得自己在阳光下尝试了一切而没有成功。为特征和故事创建独立的结构而不是匿名定义它们在主结构中?

是更好的选择。

综合文字必须从初始化的类型开始。现在,显然,匿名结构非常笨拙,因为您会重复相同的结构定义,因此最好不要使用匿名类型:

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

最新更新