结构体:
1、用来自定义复杂数据结构
2、struct里面可以包含多个字段(属性)
3、struct类型可以定义方法,注意和函数的区分
4、strucr类型是值类型
5、struct类型可以嵌套
6、go语言中没有class类型,只有struct类型 struct声明:
type 标识符 struct{
field1 type
field2 type
}
例子:
type Student struct{
Name string
Age int
Score int
} 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.Sore) struct定义的三种形式 初始化的三种方式
a、var stu Student
b、var stu *Student=new(Student)
c、var stu *Student=&Student{}
其中b和c返回的都是指向结构体的指针,访问形式如下:
a、stu.Name、stu.Age 和stu.Score 或者(*stu).Name、 (*stu).Age等
如果是指针形式可以用上面的普通的方式访问,其实就自动转化为指针访问的形式
package main
import (
"fmt"
)
type Student struct{
Name string
Age int
score float32
}
func main(){
//声明方式一
var stu Student
stu.Name="hua"
stu.Age=18
stu.score=80
//声明方式二
var stu1 *Student =&Student{
Age:20,
Name:"hua",
}
//声明方式三
var stu3 =Student{
Age:20,
Name:"hua",
}
fmt.Printf(stu1.Name)
fmt.Printf(stu3.Name)
}
struct内存布局
例子:
package main
import(
"fmt"
)
type Student struct{
Name string
Age int
score float32
}
func main(){
var stu Student
stu.Name="hua"
stu.Age=18
stu.score=80
fmt.Print(stu)
fmt.Printf("Name:%p\n",&stu.Name)
fmt.Printf("Age:%p\n",&stu.Age)
fmt.Printf("score:%p\n",&stu.score)
}
{hua 18 80}Name:0xc04204a3a0
Age:0xc04204a3b0
score:0xc04204a3b8
这里int32是4字节,64是8字节
链表的定义:
type Student struct{
name string
next* Student
}
每个节点包含下一个节点的地址,这样把所有的节点串起来,通常把链表中的每一个节点叫做链表头
遍历到最后一个元素的时候有个特点,就是next这个指针指向的是nil,可以从这个特点来判断是否是链表结束
单链表的特点:只有一个字段指向后面的结构体
单链表只能从前往后遍历
双链表的特点:有两个字段,分别指向前面和后面的结构体
双链表可以双向遍历 链表操作:
1、生成链表及遍历链表操作