Initalizing the nested anonymous structures

2020-05-10 08:51发布

问题:

I am having a json as

{
"fields": ["time","id","status","customerId","additionalDetail"],
"pageInfo": {"start": 0, "rows": 1000}
}

I wanted to Marshal my structure to above json and create the structure as below -

type RBody struct {
Fields []string `json:"fields"`
PageInfo struct {
    Start int `json:"start"`
    Rows int `json:"start"`
    } `json:"pageInfo"`
}

I am having trouble in initializing the above structure. I am not sure how to initialize the anonymous struct in below fashion :

bd := RBody {
Fields : []string{"time","id","status","customerId","additionalDetail"},
PageInfo : ???
}

I worked around this by creating a separate structure for page info and attaching that with parent struct. However there's got to be some way to perform the initialisation of the anonymous nested struct, in the same way I did with Fields (string slice) above. Can anyone redirect me to some guide to do that ?

回答1:

This works, but it is ugly:

bd := RBody { Fields :  []string{"time","id","status","customerId","additionalDetail"},
PageInfo : struct {Start int `json:"start"`
Rows int `json:"rows"`} {Start:1,Rows:2}}

I suggest you either name the anonymous struct, or initialize Fields in the declaration, and PageInfo using assignments later.



标签: go struct