Create an object from nested struct definition in GoLang?

Issue

Is there a way to create an object from a nested struct type

func main() {
    car := Car{}
    var wheel Car.Wheel
}

type Car struct {
    Wheel struct {
        name string
    }
}

I have a deep nested json. I am interested in operating on many of these nested structs separately.
I want to access the struct definition through the “root” definition . Something like Car.Wheel instead of explicitly defining type Wheel struct for many of my nested objects in the json

Solution

It is invalid syntax in Golang to define a type within a type. If you tried this you would get the following errors:

syntax error: unexpected type, expecting field name or embedded type
syntax error: non-declaration statement outside function body

You essentially have two options here:

  1. If you need the intermediate types then you’ll need to define each separately, although you can choose not to export them if you don’t want to clutter up code outside of the package you’re working with.
  2. If you only want the nested JSON itself, you could try working with the payload prior to deserialization to extract the data you want and thereby avoid defining all the intermediate types.
var data = "{\"Car\": {\"Wheel\": {\"name\": \"derp\"}}}"

var raw map[string]interface{}
json.Unmarshal([]byte(data), &raw)
fmt.Print(raw)
// map[Car:map[Wheel:map[name:derp]]]

Answered By – Woody1193

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.