💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
:-: Go中的struct 1. ⽤用来⾃自定义复杂数据结构 2. struct⾥里里⾯面可以包含多个字段(属性),字段可以是任意类型 3. struct类型可以定义⽅方法,注意和函数的区分 4. struct类型是值类型 5. struct类型可以嵌套 6. Go语⾔言没有class类型,只有struct类型 1. struct 声明: struct的定义 type 标识符 struct { field1 type field2 type } type Student struct { Name string Age int Score int } 2、定义 struct 中字段访问:和其他语⾔言⼀一样,使⽤用点 struct的定义 var stu Student stu.Name = “tony” stu.Age = 18 stu.Score=20 fmt.Printf(“name=%s age=%d score=%d”, stu.Name, stu.Age, stu.Score 3、struct定义的三种形式: struct的定义 a. var stu Student b. var stu *Student = new (Student) c. var stu *Student = &Student{} 1)其中b和c返回的都是指向结构体的指针,访问形式如下: a. stu.Name、stu.Age和stu.Score或者 (*stu).Name、(*stu).Age等 4、struct的内存布局:struct中的所有字段在内存是连续的,布局如下: ![](https://box.kancloud.cn/c75caed813a8a36565d744e7cdb502fe_816x367.png) 5、链表定义 type Student struct { Name string Next* Student } 每个节点包含下⼀一个节点的地址,这样把所有的节点串串起来了了,通常把 链表中的第⼀一个节点叫做链表头 6、双链表定义 type Student struct { Name string Next* Student Prev* Student } 如果有两个指针分别指向前⼀一个节点和后⼀一个节点,我们叫做双链表 7、二叉树定义 struct的初始化 type Student struct { Name string left* Student right* Student } 如果每个节点有两个指针分别⽤用来指向左⼦子树和右⼦子树,我们把这样的 结构叫做⼆二叉树 8、结构体是⽤用户单独定义的类型,不不能和其他类型进⾏行行强制转换 struct的初始化 type Student struct { Number int } type Stu Student //alias var a Student a = Student(30) var b Stu a = b 9、golang中的struct没有构造函数,⼀一般可以使⽤用工厂模式来解决这个问题 Package model type student struct { Name stirng Age int } func NewStudent(name string, age int) *student { return &student{ Name:name, Age:age, } } Package main S := new (student) S := model.NewStudent(“tony”, 20) 10、再次强调: 1. make ⽤用来分配map、slice、channel类型的内存 2. new⽤用来分配值类型的内存 11、struct中的tag 我们可以为struct中的每个字段,写上⼀一个tag。这个tag可以通过反射的 机制获取到,最常⽤用的场景就是json序列列化和反序列列化 type student struct { Name stirng `json=“name”` Age int `json=“age”` } 12、结构体中字段可以没有名字,即匿匿名字段 type Car struct { Name stirng Age int } type Train struct { Car Start time.Time int }