1.用来定义复杂数据结构
2.struct里面可以包含多个字段(属性)
3.struct类型可以定义方法,注意和函数的区分。
4.struct类型是值类型
5.struct类型可以嵌套
6.Go语言没有class类型,只有struct类型
package main import "fmt" //声明结构体 type Student struct { Name string Age int Score int } func main() { //struct字段访问,使用“点”访问 var stu Student stu.Name = "yuchao" stu.Age = 18 stu.Score = 99 fmt.Printf("name=%s age=%d scrore=%d", stu.Name, stu.Age, stu.Score) }
定义struct的三种形式:
package main import "fmt" //声明结构体 //字段名和函数名一样,首字母大写,在包外可以访问 type Student struct { Name string Age int Score float32 } func main() { //struct字段访问,使用“点”访问 var stu Student //var stu *Student = new(Student) //var stu *Student = &Student{ } stu.Name = "yuchao" stu.Age = 18 stu.Score = 99 //fmt.Println(stu) //默认结构 {yuchao 18 99.1} //fmt.Printf("name=%s age=%d scrore=%d", stu.Name, stu.Age, stu.Score) var stu1 *Student = &Student{ Age: 20, Name: "chao", } var stu3 = Student{ Age: 20, Name: "hua", } fmt.Println(stu1) fmt.Println(stu3.Name) fmt.Printf("Name:%p\n", &stu.Name) fmt.Printf("age:%p\n", &stu.Age) fmt.Printf("score:%p\n", &stu.Score) }
var stu Student var stu *Student = new(Student) var stu *Student = &Student{ }
struct的内存布局,struct中的所有字段在内存是连续的,布局如下:
有疑问加站长微信联系(非本文作者)