go 匿名struct定义与初始化

匿名struct定义与初始化案例

// filename test.go
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"` // 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
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值