结构体嵌套

一个结构体中可以嵌套包含另一个结构体或结构体指针。

  1. //结构体的嵌套
  2. //定义 地址 结构体类型
  3. type address struct {
  4. province string
  5. city string
  6. }
  7. //定义 学生 结构体类型
  8. type student struct {
  9. name string
  10. age int
  11. add address //嵌套 地址 结构体
  12. }
  13. func main() {
  14. stu1 := student{
  15. name: "小张",
  16. age: 18,
  17. add: address{
  18. province: "河北",
  19. city:"台台",
  20. },
  21. }
  22. fmt.Println(stu1)
  23. fmt.Println(stu1.add.province)
  24. }

匿名字段嵌套

  1. //
  2. //匿名字段结构体的嵌套
  3. type address struct {
  4. province string
  5. city string
  6. }
  7. type email struct {
  8. province string
  9. }
  10. type student struct {
  11. name string
  12. age int
  13. address //嵌入匿名结构体 address
  14. email //嵌入匿名结构体 email
  15. }
  16. func main() {
  17. stu1 := student{
  18. name: "小张",
  19. age: 18,
  20. address: address{
  21. province: "河北",
  22. city:"台台",
  23. },
  24. email: email{
  25. province:"hebei",
  26. },
  27. }
  28. fmt.Println(stu1)
  29. fmt.Println(stu1.province) //当匿名字段可以直接调用
  30. fmt.Println(stu1.email.province) //当匿名字段有冲突时必须显示调用
  31. }