struct 内存布局
struct 是值类型,直接指向 struct 的内存空间
字段=属性=field
没赋值的字段初始化为它们相应的 0 值
map、slice赋值前要 make
struct 默认是值拷贝
改变一个实例的字段不会影响另一个。
monster2 := monster1
这句代码内存变化如下:直接拷贝牛魔王,再在上面修改
结构体指针
var person *Person = &Person{
}
//因为person 是一个指针,因此标准的访问字段的方法
// (*person).Name = "scott"
// go的设计者为了程序员使用方便,也可以 person.Name = "scott"
// 原因和上面一样,底层会对 person.Name = "scott" 进行处理, 会加上 (*person)
(*person).Name = "scott"
person.Name = "scott~~"
(*person).Age = 88
person.Age = 10
fmt.Println(*person)
(*person).Name = “scott” -----底层实现仍然是它
person.Name = “scott~~”-----方便程序员的简便写法
细节
(1)所有字段在内存中是连续分配的
package main
import "fmt"
//结构体
type Point struct {
x int
y int
}
//结构体
type Rect struct {
leftUp, rightDown Point
}
//结构体
type Rect2 struct {
leftUp, rightDown *Point
}
func main() {
r1 := Rect{
Point{
1,2}, Point{
3,4}}
//r1有四个int, 在内存中是连续分布
//打印地址
fmt.Printf("r1.leftUp.x 地址=%p r1.leftUp.y 地址=%p r1.rightDown.x 地址=%p r1.rightDown.y 地址=%p \n",
&r1.leftUp.x, &r1.leftUp.y, &r1.rightDown