我有这样的结构:
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"`
}
我想像这样为它分配值: -
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
但是提供的错误是 data.Accounting.LastName undefined
虽然相同的代码适用于
type AutoGenerated struct { FirstName string `json:"firstName"` LastName string `json:"lastName"` Age int `json:"age"` }
我分配了这样的值: -
data := AutoGenerated{}
data.LastName = "Apple2"
data.FirstName = "Apple1"
data.Age = 20
请不要手动分配值我必须从其他功能中获取值。
答案 0 :(得分:0)
你的内在结构是切片。使用它:
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"`
或者,如果每个结构需要多个销售或会计,则必须初始化切片并按索引引用它们。
答案 1 :(得分:0)
在data
类型的AutoGenerated
对象中,data.Accounting
是一个结构片段。在使用data.Accounting
切片之前,您需要初始化它。一个示例用法是:
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"`
}
然后为结构赋值:
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})