【问题标题】:Initializing Nested Maps in Struct在 Struct 中初始化嵌套映射
【发布时间】:2018-04-03 19:48:15
【问题描述】:

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

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

【问题讨论】:

标签: dictionary go struct nested


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多