29

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

mquemazz
  • 763
  • 3
  • 12
  • 18

2 Answers2

34

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)
}
Not_a_Golfer
  • 47,012
  • 14
  • 126
  • 92
  • Perfect, I guess until the moment I am not used enough to the embedding thing and nested structs in Go, after all years dealing with java, this is completely new to me, but thanks a lot :D – mquemazz Feb 12 '15 at 13:32
6

Full example with everything written out explicitly:

state := State{
    id: "Independent Republic of Stackoverflow",
    Cities: Cities{
        cities: []City{
            City{
                id: "Postington O.P.",
            },
        },
    },
}
thwd
  • 23,956
  • 8
  • 74
  • 108