-2

I am very new to Golang and I am trying to do something that I thought would be easy enough and yet I am having trouble accomplishing it. Given the following code

package main

import (
    "encoding/json"
    "fmt"
    "os"
)


type Example struct {
    Data []struct {
        Name                    string   `json:"Name"`
        Onboarded               bool     `json:"Onboarded"`
    } `json:"data"`
}


func main() {

    // This is what I am trying to figure out.
    // How do I properly instantiate the Example type struct with values ? 
    // I'm not getting the Data part.
    example := Example{
        Data: ...
    }
}

Any help is appreciated. Thanks.

nabello
  • 716
  • 11
  • 29

2 Answers2

2

A composite literal using anonymous types can be very verbose. Simplify the job by declaring types:

type Example struct {
    Data []Employee `json:"data"`
}

type Employee struct {
    Name                    string   `json:"Name"`
    Onboarded               bool     `json:"Onboarded"`
}

Here's the composite literal with those types:

example := Example{
    Data: []Employee{
       {Name: "Russ C.", Onboarded: true},
       {Name: "Brad F.", Onboarded: false},
    },
}
1

I think a (way) more idiomatic solution would be to define a type for the nested struct. Anyway, you can do this:

example := Example{
        Data: []struct {
            Name      string `json:"Name"`
            Onboarded bool   `json:"Onboarded"`
        }{
            {Name: "Idk", Onboarded: false},
            {Name: "More", Onboarded: true},
        },
    }

Ideally, you'd want to do something like this:

type Example struct {
    Data []ExampleNested `json:"data"`
}

type ExampleNested struct {
    Name      string `json:"Name"`
    Onboarded bool   `json:"Onboarded"`
}

And then:

example := Example{
        Data: []ExampleNested{
            {Name: "Idk", Onboarded: false},
            {Name: "More", Onboarded: false},
        },
    }
Riwen
  • 4,734
  • 2
  • 19
  • 31