Initialize nested struct definition in Golang if i

2019-07-29 22:24发布

问题:

I have struct like this:

type AutoGenerated struct {
 Accounting []struct {
    FirstName string `json:"firstName"`
    LastName string `json:"lastName"`
    Age int `json:"age"`
} `json:"accounting"`
Sales []struct {
    FirstName string `json:"firstName"`
    LastName string `json:"lastName"`
    Age int `json:"age"`
} `json:"sales"`

}

I want to assign values to it like this:-

data := AutoGenerated{}
data.Accounting.LastName = "Apple2"
data.Accounting.FirstName = "Apple1"
data.Accounting.Age = 20
data.Sales.LastName = "Ball2"
data.Sales.FirstName = "Ball1"
data.Sales.Age = 30

But is is giving error which is data.Accounting.LastName undefined

Although same code is working fine for

type AutoGenerated struct {
    FirstName string `json:"firstName"`
    LastName string `json:"lastName"`
    Age int `json:"age"`
}

Where I assigned the values like this:-

data := AutoGenerated{}
data.LastName = "Apple2"
data.FirstName = "Apple1"
data.Age = 20

Please don't assign values manually I have to take values from other function.

回答1:

Your inner structs are slices. Either use this:

type AutoGenerated struct {
 Accounting struct {
    FirstName string `json:"firstName"`
    LastName string `json:"lastName"`
    Age int `json:"age"`
} `json:"accounting"`
Sales struct {
    FirstName string `json:"firstName"`
    LastName string `json:"lastName"`
    Age int `json:"age"`
} `json:"sales"`

Or if you need to have more than one Sale or Accounting per struct then you have to initialize the slices and refer to them by index.



回答2:

In your object data of AutoGenerated type, data.Accounting is a slice of structs. Before you can use data.Accounting slice, you'll need to initialize it. An example usage would be:

type AutoGenerated struct {
 Accounting []Account `json:"accounting"`
 Sales []struct {
    FirstName string `json:"firstName"`
    LastName string `json:"lastName"`
    Age int `json:"age"`
 } `json:"sales"`
}

// defined separately for better readability
type Account struct {
    FirstName string `json:"firstName"`
    LastName string `json:"lastName"`
    Age int `json:"age"`
}

Then to assign values to the struct:

a := AutoGenerated{}
a.Accounting = make([]Account, 1) // create the slice of appropriate length
// append values to it
a.Accounting = append(a.Accounting, Account{"firstname", "lastname", 30})


标签: json go struct