golang:结构体指针类型匿名字段

雨点打透心脏的1/2处 2023-02-16 12:28 78阅读 0赞
  1. package main
  2. import "fmt"
  3. type Person struct {
  4. name string
  5. sex byte
  6. age int
  7. }
  8. type Student struct {
  9. *Person
  10. id int
  11. addr string
  12. }
  13. func main() {
  14. s1 := Student{
  15. &Person{
  16. name: "a",
  17. sex: 'm',
  18. age: 18,
  19. },
  20. 11,
  21. "aaa",
  22. }
  23. fmt.Println(s1.name, s1.sex, s1.age, s1.id, s1.addr)
  24. var s2 Student
  25. s2.Person = new(Person)
  26. s2.name = "yoyo"
  27. s2.sex = 'm'
  28. s2.age = 18
  29. s2.id = 222
  30. s2.addr = "sz"
  31. fmt.Println(s2, s2.name, s2.sex, s2.age, s2.id, s2.addr, s2.Person, &s2.Person)
  32. var s3 Student
  33. s3.Person = new(Person)
  34. s3.Person.name = "aaa"
  35. s3.Person.sex = 'f'
  36. s3.Person.age = 18
  37. s3.id = 11
  38. s2.addr = "sz"
  39. fmt.Println(s3, s3.name, s3.sex, s3.age, s3.id, s3.addr, s3.Person, &s3.Person)
  40. }

结果

  1. a 109 18 11 aaa
  2. {
  3. 0xc000004500 222 sz} yoyo 109 18 222 sz &{
  4. yoyo 109 18} 0xc0000044e0
  5. {
  6. 0xc000004580 11 } aaa 102 18 11 &{
  7. aaa 102 18} 0xc000004560

发表评论

表情:
评论列表 (有 0 条评论,78人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Golang学习笔记 结构指针

    Golang是一门很特殊的语言,虽然它出生比较晚,但是在很多地方却和现在的编程语言有所不同。现在的编程语言要么是函数式的、要么是面向对象的,而Go语言却有指针、结构体这些概念,