From c96b7cebe085ab62174918160ba31baf7f0eb771 Mon Sep 17 00:00:00 2001 From: Shikong <919411476@qq.com> Date: Sun, 3 Oct 2021 02:11:04 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20=E5=B5=8C=E5=A5=97=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E4=BD=93=E3=80=81=E5=8C=BF=E5=90=8D=E5=B5=8C=E5=A5=97=E7=BB=93?= =?UTF-8?q?=E6=9E=84=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base/struct/nested/main.go | 59 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 base/struct/nested/main.go diff --git a/base/struct/nested/main.go b/base/struct/nested/main.go new file mode 100644 index 0000000..43fc3a0 --- /dev/null +++ b/base/struct/nested/main.go @@ -0,0 +1,59 @@ +package main + +import "fmt" + +// Person +// 嵌套结构体 +type Person struct { + Name string + Age int + Address Address +} + +// Person2 +// 匿名 嵌套结构体 +type Person2 struct { + Name string + Age int + Address +} + +type Company struct { + Name string + Address Address +} + +type Address struct { + Province string + City string +} + +func main() { + p1 := &Person{ + Name: "张三", + Age: 20, + Address: Address{ + Province: "广东", + City: "广州", + }, + } + + fmt.Printf("%#v\n", p1) + fmt.Printf("%v %v\n", p1.Address.Province, p1.Address.City) + + fmt.Println("=========================================================") + + p2 := &Person2{ + Name: "李四", + Age: 20, + Address: Address{ + Province: "广东", + City: "广州", + }, + } + fmt.Printf("%#v\n", p2) + fmt.Printf("%v %v\n", p2.Address.Province, p2.Address.City) + // 匿名结构体 先在自己的 结构体中 寻找 字段 若 找不到 则 从 匿名嵌套结构体中 查找 + // 如果 多个匿名嵌套结构体中 有字段冲突 则只能使用 类型名.字段名 访问 + fmt.Printf("%v %v\n", p2.Province, p2.City) +}