gpt4 book ai didi

dictionary - 在结构中初始化嵌套映射

转载 作者:IT王子 更新时间:2023-10-29 02:31:47 25 4
gpt4 key购买 nike

我是 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 创建独立的结构比在主结构中匿名定义它们更好吗?

最佳答案

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

关于dictionary - 在结构中初始化嵌套映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49638061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com