1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
|
package main
import "fmt"
// 基础结构体
type Address struct {
Street string
City string
ZipCode string
Country string
}
type Contact struct {
Phone string
Email string
}
// 嵌入结构体(匿名字段)
type Person struct {
Name string
Age int
Address // 匿名嵌入
Contact // 匿名嵌入
}
// 命名嵌入
type Employee struct {
ID int
Name string
HomeAddress Address // 命名嵌入
WorkAddress Address // 命名嵌入
ContactInfo Contact // 命名嵌入
}
// 方法定义
func (a Address) String() string {
return fmt.Sprintf("%s, %s %s, %s", a.Street, a.City, a.ZipCode, a.Country)
}
func (c Contact) String() string {
return fmt.Sprintf("Phone: %s, Email: %s", c.Phone, c.Email)
}
// 嵌入结构体的方法提升
type Point struct {
X, Y float64
}
func (p Point) Distance() float64 {
return math.Sqrt(p.X*p.X + p.Y*p.Y)
}
type Circle struct {
Point // 嵌入Point
Radius float64
}
func main() {
// 1. 匿名嵌入的使用
person := Person{
Name: "张三",
Age: 30,
Address: Address{
Street: "中关村大街1号",
City: "北京",
ZipCode: "100080",
Country: "中国",
},
Contact: Contact{
Phone: "13800138000",
Email: "zhangsan@example.com",
},
}
fmt.Printf("人员信息: %+v\n", person)
// 2. 直接访问嵌入字段
fmt.Printf("姓名: %s\n", person.Name)
fmt.Printf("城市: %s\n", person.City) // 直接访问Address.City
fmt.Printf("电话: %s\n", person.Phone) // 直接访问Contact.Phone
// 3. 通过嵌入类型访问
fmt.Printf("地址: %s\n", person.Address.String())
fmt.Printf("联系方式: %s\n", person.Contact.String())
// 4. 修改嵌入字段
person.City = "上海"
person.Email = "zhangsan@newcompany.com"
fmt.Printf("修改后的城市: %s\n", person.City)
fmt.Printf("修改后的邮箱: %s\n", person.Email)
// 5. 命名嵌入
employee := Employee{
ID: 1001,
Name: "李四",
HomeAddress: Address{
Street: "朝阳路100号",
City: "北京",
ZipCode: "100020",
Country: "中国",
},
WorkAddress: Address{
Street: "金融街35号",
City: "北京",
ZipCode: "100033",
Country: "中国",
},
ContactInfo: Contact{
Phone: "13900139000",
Email: "lisi@company.com",
},
}
fmt.Printf("员工信息: %+v\n", employee)
fmt.Printf("家庭地址: %s\n", employee.HomeAddress.String())
fmt.Printf("工作地址: %s\n", employee.WorkAddress.String())
// 6. 方法提升
circle := Circle{
Point: Point{X: 3, Y: 4},
Radius: 5,
}
fmt.Printf("圆心坐标: (%.1f, %.1f)\n", circle.X, circle.Y)
fmt.Printf("圆心到原点距离: %.2f\n", circle.Distance()) // 方法提升
fmt.Printf("半径: %.1f\n", circle.Radius)
// 7. 字段名冲突的处理
type A struct {
Name string
}
type B struct {
Name string
}
type C struct {
A
B
Name string // 覆盖嵌入的Name字段
}
c := C{
A: A{Name: "A的名字"},
B: B{Name: "B的名字"},
Name: "C的名字",
}
fmt.Printf("C.Name: %s\n", c.Name) // C的名字
fmt.Printf("C.A.Name: %s\n", c.A.Name) // A的名字
fmt.Printf("C.B.Name: %s\n", c.B.Name) // B的名字
}
|