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