【问题标题】:go append to an interface key/field which is a map附加到一个接口键/字段,它是一个映射
【发布时间】:2016-11-10 00:39:51
【问题描述】:

我的问题是关于附加到作为接口的字段/键的映射。这是构建 JSON 对象所必需的。我正在使用map[string]interface{} 能够将任何结构类型附加到它。我不确定这是否是正确的方法,因为我仍在学习 Go,但我找不到更好的方法。以下是游乐场的链接:
https://play.golang.org/p/cxpSep8OQD.

我想我需要使用类型积累,但我不明白如何。任何帮助都会很有用。

【问题讨论】:

    标签: go


    【解决方案1】:

    如果您只有Group 值,则将outJson 声明为*Group 的映射:

    outJson := make(map[string]*Group, len(groups))
    

    Playground Example

    如果映射可以包含不同的值类型,则使用type assertion 访问组:

        g, ok := outJson["a"].(*Group)
        if !ok {
            panic("handle error a better way")
        }
        g.Hosts = append(g.Hosts, "hostname")
    

    Playground Example

    【讨论】:

    • 不幸的是,我还有其他类型。实际上只有一种其他类型。
    • 我做到了!感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多