Home > Back-end >  Create an object from nested struct definition in GoLang?
Create an object from nested struct definition in GoLang?

Time:05-10

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

CodePudding user response:

Are you looking for something like this:

package main

import "fmt"

type Car struct {
    model string
    wheel Wheel
}

type Wheel struct {
    name string
}

func main() {
    car := Car{model: "Toyota"}
    car.wheel.name = "my wheel"

    fmt.Println("car model: ", car.model)
    fmt.Println("car wheel name:", car.wheel.name)
}

CodePudding user response:

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]]]
  • Related