douqiao2008 2015-02-12 13:04
浏览 96
已采纳

在golang中的嵌套结构中初始化结构数组

I am wondering how can I define and initialize and array of structs inside a nested struct, for example:

type State struct {
    id string `json:"id" bson:"id"`
    Cities 
}

type City struct {
    id string `json:"id" bson:"id"`
}

type Cities struct {
    cities []City
}

Now how can I Initialize such a structure and if someone has a different idea about how to create the structure itself.

Thanks

  • 写回答

2条回答 默认 最新

  • dongyan1841 2015-02-12 13:11
    关注

    In your case the shorthand literal syntax would be:

    state := State {
        id: "CA",
        Cities:  Cities{
            []City {
                {"SF"},
            },
        },
    }
    

    Or shorter if you don't want the key:value syntax for literals:

    state := State {
        "CA", Cities{
            []City {
                {"SF"},
            },
        },
    }    
    

    BTW if Cities doesn't contain anything other than the []City, just use a slice of City. This will lead to a somewhat shorter syntax, and remove an unnecessary (possibly) layer:

    type State struct {
        id string `json:"id" bson:"id"`
        Cities []City
    }
    
    type City struct {
        id string `json:"id" bson:"id"`
    }
    
    
    func main(){
        state := State {
            id: "CA",
            Cities:  []City{
                 {"SF"},
            },
        }
    
        fmt.Println(state)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?