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

0

2 Answers 2

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

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
6

Full example with everything written out explicitly:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.