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!