Dictionary 在结构中初始化嵌套映射
我是一个新手,正在使用来自REST端点的一些数据。我已经取消了json的编组,我正在尝试使用两个嵌套映射填充自定义结构:Dictionary 在结构中初始化嵌套映射,dictionary,go,struct,nested,Dictionary,Go,Struct,Nested,我是一个新手,正在使用来自REST端点的一些数据。我已经取消了json的编组,我正在尝试使用两个嵌套映射填充自定义结构: type EpicFeatureStory struct { Key string Description string Features map[string]struct { Name string Description string Stories ma
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创建独立的结构,而不是在主结构中匿名定义它们?必须从初始化的类型开始。现在,很明显,匿名结构很难使用,因为您要重复相同的结构定义,所以最好不要使用匿名类型:
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)
}
必须以正在初始化的类型开头。现在,很明显,匿名结构很难使用,因为您要重复相同的结构定义,所以最好不要使用匿名类型:
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)
}
为了说明使用匿名结构定义的不方便,下面是一个示例来说明使用匿名结构定义的不方便,下面是的.Duplicate的示例。