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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看