结构体嵌套
一个结构体中可以嵌套包含另一个结构体或结构体指针。
//结构体的嵌套
//定义 地址 结构体类型
type address struct {
province string
city string
}
//定义 学生 结构体类型
type student struct {
name string
age int
add address //嵌套 地址 结构体
}
func main() {
stu1 := student{
name: "小张",
age: 18,
add: address{
province: "河北",
city:"台台",
},
}
fmt.Println(stu1)
fmt.Println(stu1.add.province)
}
匿名字段嵌套
//
//匿名字段结构体的嵌套
type address struct {
province string
city string
}
type email struct {
province string
}
type student struct {
name string
age int
address //嵌入匿名结构体 address
email //嵌入匿名结构体 email
}
func main() {
stu1 := student{
name: "小张",
age: 18,
address: address{
province: "河北",
city:"台台",
},
email: email{
province:"hebei",
},
}
fmt.Println(stu1)
fmt.Println(stu1.province) //当匿名字段可以直接调用
fmt.Println(stu1.email.province) //当匿名字段有冲突时必须显示调用
}