赋值操作(未使用指针)
package main
import "fmt"
//Animal ..
type Animal struct {
Name string
}
//Bird ..
type Bird struct {
Animal Animal
Legs int
}
//Sparrow ..
type Sparrow struct {
Bird Bird
Size string
}
func main() {
var s Sparrow = Sparrow{
Bird : Bird{
Animal: Animal{
Name: "小麻雀",
},
Legs: 2,
},
Size: "small",
}
s1 := s
s1.Bird.Animal.Name = "假麻雀"
s1.Bird.Legs = 16
s1.Size = "big"
b1 := s.Bird
a1 := s.Bird.Animal
var b2 Bird = s.Bird
var a2 Animal = s.Bird.Animal
b1.Legs = 4
b2.Legs = 8
a1.Name = "大小麻雀"
a2.Name = "小小小小麻雀"
fmt.Printf("%+v\n", s)
fmt.Printf("%+v\n", s1)
fmt.Printf("%+v\n", b1)
fmt.Printf("%+v\n", b2)
fmt.Printf("%+v\n", a1)
fmt.Printf("%+v\n", a2)
}
//结果如下
{Bird:{Animal:{Name:小麻雀} Legs:2} Size:small} //s
{Bird:{Animal:{Name:假麻雀} Legs:16} Size:big} //s1
{Animal:{Name:小麻雀} Legs:4} //b1
{Animal:{Name:小麻雀} Legs:8} //b2
{Name:大小麻雀} //a1
{Name:小小小小麻雀} //a2
说明未使用指针情况下,通过结构体赋值后的结构体,改变对原来没有影响
赋值操作(指针)
func main() {
var s Sparrow = Sparrow{
Bird : &Bird{
Animal: &Animal{
Name: "小麻雀",
},
Legs: 2,
},
Size: "small",
}
s1 := s
s1.Bird.Animal.Name = "假麻雀"
s1.Bird.Legs = 16
s1.Size = "big"
b1 := s.Bird
a1 := s.Bird.Animal
var b2 Bird = *s.Bird
var a2 Animal = *s.Bird.Animal
b1.Legs = 4
b2.Legs = 8
a1.Name = "大小麻雀"
a2.Name = "小小小小麻雀"
fmt.Printf("%+v, %p\n", s, s.Bird)
fmt.Printf("%+v, %p\n", s1, s.Bird)
fmt.Printf("%+v, %p\n", *b1, b1)
fmt.Printf("%+v, %p\n", b2, &b2)
fmt.Printf("%+v, %p\n", *a1, a1)
fmt.Printf("%+v, %p\n", a2, &a2)
}
//Animal ..
type Animal struct {
Name string
}
//Bird ..
type Bird struct {
Animal *Animal
Legs int
}
//Sparrow ..
type Sparrow struct {
Bird *Bird
Size string
}
//结果
{Bird:0xc0000381f0 Size:small}, 0xc0000381f0 //s
{Bird:0xc0000381f0 Size:big}, 0xc0000381f0 //s1
{Animal:0xc000038200 Legs:4}, 0xc0000381f0 //b1
{Animal:0xc000038200 Legs:8}, 0xc000038210 //b2
{Name:大小麻雀}, 0xc000038200 //a1
{Name:小小小小麻雀}, 0xc000038220 // a2
可以看出a1地址在b1的指针中, b1地址在s和s1的指针中,因此指针的情况下不能直接复制
不过可以看a2和b2地址和a1,b1地址