匿名struct定义与初始化案例
package main
import "fmt"
type Persion struct {
Name string `json:"name"`
Age int `json:"age"`
Ext *struct {
Data *struct {
Sex string `json:"sex"`
} `json:"data,omitempty"`
Hobby string `json:"hobby"`
} `json:"ext,omitempty"`
}
func main() {
ManyPersion := []Persion{
{
Name: "zhangsan",
Age: 18,
Ext: &struct {
Data *struct {
Sex string "json:\"sex\""
} "json:\"data,omitempty\""
Hobby string "json:\"hobby\""
}{
Data: &struct {
Sex string "json:\"sex\""
}{
Sex: "boy",
},
Hobby: "play basketball",
},
},
{
Name: "lishanshan",
Age: 16,
Ext: &struct {
Data *struct {
Sex string "json:\"sex\""
} "json:\"data,omitempty\""
Hobby string "json:\"hobby\""
}{
Data: &struct {
Sex string "json:\"sex\""
}{
Sex: "girl",
},
Hobby: "play the piano",
},
},
{
Name: "wusan",
Age: 20,
},
}
fmt.Println(ManyPersion)
for index, p := range ManyPersion {
fmt.Println("Index=", index, "Start")
fmt.Println("Persion=", p)
if p.Ext != nil {
fmt.Println("Hobby=", p.Ext.Hobby)
if p.Ext.Data != nil {
fmt.Println("Sex=", p.Ext.Data.Sex)
}
}
fmt.Println("Index=", index, "End")
}
}
如何案例运行结果
$ go run test.go
[{zhangsan 18 0xc00000c018} {lishanshan 16 0xc00000c030} {wusan 20 <nil>}]
Index= 0 Start
Persion= {zhangsan 18 0xc00000c018}
Hobby= play basketball
Sex= boy
Index= 0 End
Index= 1 Start
Persion= {lishanshan 16 0xc00000c030}
Hobby= play the piano
Sex= girl
Index= 1 End
Index= 2 Start
Persion= {wusan 20 <nil>}
Index= 2 End
|