Initalizing the nested anonymous structures

左心房为你撑大大i 提交于 2020-01-22 03:58:05

问题


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.



来源:https://stackoverflow.com/questions/58696604/initalizing-the-nested-anonymous-structures

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!