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.
Your inner structs are slices. Either use this:
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.
In your object
data
ofAutoGenerated
type,data.Accounting
is a slice of structs. Before you can usedata.Accounting
slice, you'll need to initialize it. An example usage would be:Then to assign values to the struct: