doumengxue7371 2018-04-03 19:48
浏览 53
已采纳

在Struct中初始化嵌套地图

I am relatively new to Go and I am consuming some data from a REST endpoint. I have unmarshaled my json and I am trying to populate a custom struct with a couple of nested maps:

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

As I iterate over my features I am trying to add them to the Features map within the struct.

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

How does one initialize the Features map in this case? I feel like have tried everything under the sun without success. Is it better Go form to create independent structs for Feature and Story rather than anonymously defining them within the main struct?

  • 写回答

1条回答 默认 最新

  • donglinxi1467 2018-04-03 19:56
    关注

    A composite literal must start with the type being initialized. Now, obviously that's pretty unwieldy with anonymous structs because you'd be repeating the same struct definition, so it would probably be better not to use an anonymous type:

    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
    }
    

    So that you can just:

    // 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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置