初始化嵌套的匿名结构

初始化嵌套的匿名结构

本文介绍了初始化嵌套的匿名结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的json为

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

我想将我的结构编组到json之上,并创建如下结构-

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 : ???
}

我通过为页面信息创建一个单独的结构并将其与父结构附加在一起来解决此问题.但是,必须有某种方法来执行 anonymous 嵌套结构的初始化,就像我对上面的 Fields (字符串切片)所做的一样.谁能将我重定向到一些指南来做到这一点?

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 ?

推荐答案

这有效,但是很丑:

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

我建议您命名匿名结构,或者在声明中初始化Fields,并在以后使用赋值初始化PageInfo.

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

这篇关于初始化嵌套的匿名结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 21:41