赋值操作(未使用指针)

  1. package main
  2. import "fmt"
  3. //Animal ..
  4. type Animal struct {
  5. Name string
  6. }
  7. //Bird ..
  8. type Bird struct {
  9. Animal Animal
  10. Legs int
  11. }
  12. //Sparrow ..
  13. type Sparrow struct {
  14. Bird Bird
  15. Size string
  16. }
  17. func main() {
  18. var s Sparrow = Sparrow{
  19. Bird : Bird{
  20. Animal: Animal{
  21. Name: "小麻雀",
  22. },
  23. Legs: 2,
  24. },
  25. Size: "small",
  26. }
  27. s1 := s
  28. s1.Bird.Animal.Name = "假麻雀"
  29. s1.Bird.Legs = 16
  30. s1.Size = "big"
  31. b1 := s.Bird
  32. a1 := s.Bird.Animal
  33. var b2 Bird = s.Bird
  34. var a2 Animal = s.Bird.Animal
  35. b1.Legs = 4
  36. b2.Legs = 8
  37. a1.Name = "大小麻雀"
  38. a2.Name = "小小小小麻雀"
  39. fmt.Printf("%+v\n", s)
  40. fmt.Printf("%+v\n", s1)
  41. fmt.Printf("%+v\n", b1)
  42. fmt.Printf("%+v\n", b2)
  43. fmt.Printf("%+v\n", a1)
  44. fmt.Printf("%+v\n", a2)
  45. }
  46. //结果如下
  47. {Bird:{Animal:{Name:小麻雀} Legs:2} Size:small} //s
  48. {Bird:{Animal:{Name:假麻雀} Legs:16} Size:big} //s1
  49. {Animal:{Name:小麻雀} Legs:4} //b1
  50. {Animal:{Name:小麻雀} Legs:8} //b2
  51. {Name:大小麻雀} //a1
  52. {Name:小小小小麻雀} //a2

说明未使用指针情况下,通过结构体赋值后的结构体,改变对原来没有影响

赋值操作(指针)

  1. func main() {
  2. var s Sparrow = Sparrow{
  3. Bird : &Bird{
  4. Animal: &Animal{
  5. Name: "小麻雀",
  6. },
  7. Legs: 2,
  8. },
  9. Size: "small",
  10. }
  11. s1 := s
  12. s1.Bird.Animal.Name = "假麻雀"
  13. s1.Bird.Legs = 16
  14. s1.Size = "big"
  15. b1 := s.Bird
  16. a1 := s.Bird.Animal
  17. var b2 Bird = *s.Bird
  18. var a2 Animal = *s.Bird.Animal
  19. b1.Legs = 4
  20. b2.Legs = 8
  21. a1.Name = "大小麻雀"
  22. a2.Name = "小小小小麻雀"
  23. fmt.Printf("%+v, %p\n", s, s.Bird)
  24. fmt.Printf("%+v, %p\n", s1, s.Bird)
  25. fmt.Printf("%+v, %p\n", *b1, b1)
  26. fmt.Printf("%+v, %p\n", b2, &b2)
  27. fmt.Printf("%+v, %p\n", *a1, a1)
  28. fmt.Printf("%+v, %p\n", a2, &a2)
  29. }
  30. //Animal ..
  31. type Animal struct {
  32. Name string
  33. }
  34. //Bird ..
  35. type Bird struct {
  36. Animal *Animal
  37. Legs int
  38. }
  39. //Sparrow ..
  40. type Sparrow struct {
  41. Bird *Bird
  42. Size string
  43. }
  44. //结果
  45. {Bird:0xc0000381f0 Size:small}, 0xc0000381f0 //s
  46. {Bird:0xc0000381f0 Size:big}, 0xc0000381f0 //s1
  47. {Animal:0xc000038200 Legs:4}, 0xc0000381f0 //b1
  48. {Animal:0xc000038200 Legs:8}, 0xc000038210 //b2
  49. {Name:大小麻雀}, 0xc000038200 //a1
  50. {Name:小小小小麻雀}, 0xc000038220 // a2

可以看出a1地址在b1的指针中, b1地址在s和s1的指针中,因此指针的情况下不能直接复制
不过可以看a2和b2地址和a1,b1地址