普通网友 2017-08-05 05:03
浏览 22

嵌入匿名结构

I'm trying to figure out how to embed an anonymous struct within another struct, for json parsing purposes.

I have an "extras" map that contains different attributes dependent on various factors. This map is a field of a larger json blob. I'd like to fully model out the various possibilities of the "extras" map so I can avoid using type assertions. I would like to have the "extras" structs be separate from the base struct (the rest of the json). I know I can do something like this:

type TestObj1 struct {
    ExtraObj `json:"extras"`
}

type ExtraObj struct {
    Foo string `json:"foo"`
}

This works great, because the json parses exactly how I would expect, and I can directly access Foo like so testObj1.Foo. The problem with this method is that now I have 2 different structs per possible "extras" variation, instead of 1. So then I could try something like this:

type TestObj2 struct {
    Extras struct {
        Foo string `json:"foo"`
    } `json:"extras"`
}

This also parses the json as expected, and gets rid of the need for 2 structs per variation. But the problem is, to access Foo, I need to go through Extras like so testObj2.Extras.Foo. I was hoping for a best of both worlds solution like so:

type TestObj3 struct {
    struct {
        Foo string `json:"foo"`
    } `json:"extras"`
}

But this is a compile error. A quick playground link I put together for this.

Is there any way to accomplish something like this, or is it not possible in the language? Your help is greatly appreciated!

  • 写回答

1条回答 默认 最新

  • donglanche9257 2019-03-02 01:11
    关注

    Try the following:

    type TestObj1 struct {
        ExO ExtraObj `json:"extras"`
    }
    
    type ExtraObj struct {
        Foo string `json:"foo"`
    }
    

    I did not test it myself, but should work.

    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行