在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

我想知道如何在嵌套结构中定义和初始化结构以及结构数组,例如: p >

  type状态结构{
 id字符串`json:“ id” bson:“ id”`
城市
} 
 
type城市结构{
 id字符串`json  :“ id” bson:“ id”`
} 
 
type城市结构{
城市[]城市
} 
  code>  pre> 
 
 

现在我该如何 初始化这样的结构,如果有人对如何自己创建结构有不同的想法。 p>

谢谢 p> div>

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

Full example with everything written out explicitly:

state := State{
    id: "Independent Republic of Stackoverflow",
    Cities: Cities{
        cities: []City{
            City{
                id: "Postington O.P.",
            },
        },
    },
}