结构体
- 结构体解释:将一个或多个变量组合到一起,形成新的类型,整个类型就是结构体
- Go语言中的结构体和C++结构体有点类似,而java和C#中类本质就是结构体
- 结构体是值类型
- 结构体定义语法
通过语法可以看出Go语言发明者明确认为结构体就是一种自定义类型
type 结构体名称 struct{
名称 类型 //成员或属性
}
结构体定义与示例
- 定义结构体
1、结构体可以定义在函数内部或函数外部(与普通变量一样),定义位置影响到结构体的访问范围
2、如果结构体定义在函数外面,结构体名称首字母是否大小写影响到结构体是否能跨包访问
3、如果结构体能跨包访问,属性首字母是否大写影响到属性是否跨包访问
type People struct { //结构体首字母大写,可以跨包访问
Name string //结构体可跨包访问前提下,属性首字母大写,则可跨包访问
Age int
}
- 声明结构体变量
由于结构体是值类型,所以声明后就会开辟内存空间
所有成员为类型对应的初始值
type People struct {
Name string
Age int
}
func main() {
var peo People
fmt.Println(peo) //输出:{ 0}
fmt.Printf("%p",&peo) //输出内存地址:0xc000004480
}
- 可以直接给结构体多个属性赋值
type People struct {
Name string
Age int
}
func main() {
var peo People
//按照结构体中属性的顺序进行赋值,可以省略属性名称
peo = People{"theoutsider", 17}
fmt.Println(peo) //{theoutsider 17}
//明确指定给哪些属性赋值,可以都赋值,也可以只给其中一部分赋值
peo = People{Age: 18, Name: "js"}
fmt.Println(peo) //{js 18}
}
- 也可以通过结构体变量名称获取到属性进行赋值或查看
type People struct {
Name string
Age int
}
func main() {
var peo People
peo.Name = "theoutsider"
peo.Age = 17
fmt.Println(peo) //{theoutsider 17}
fmt.Println(peo.Name) //theoutsider
fmt.Println(peo.Age) //17
}
结构体的判断
- 双等(==)判断结构体中内容是否相等
type People struct {
Name string
Age int
}
func main() {
p1 := People{"smallming", 17}
p2 := People{"smallming", 17}
fmt.Printf("%p %p\n", &p1, &p2) //输出地址相同:0xc000004480 0xc0000044a0
fmt.Println(p1 == p2) //输出:true
}
结构体指针
- 由于结构体是值类型,在方法传递时,希望传递结构体地址,可以使用结构体指针完成
- 可以结合new(T)函数创建结构体指针
type People struct {
Name string
Age int
}
func main() {
peo :=new(People)
//因为结构体本质是值类型,所以创建结构体指针时已经开辟了内存空间
fmt.Println(peo == nil) //输出false
peo.Name = "theoutsider"
fmt.Println(peo) //输出&{theoutsider 0}
peo1 := peo
peo1.Name = "js"
fmt.Println(peo1, peo) //输出:&{js 0} &{js 0}
}
- 如果不想使用new(T)函数,可以直接声明结构体指针并赋值
type People struct {
Name string
Age int
}
func main() {
//声明结构体指针
var peo *People
//给结构体指针赋值
peo = &People{"theoutsider", 17}
/*
上面代码使用短变量方式如下
peo = &People{"theoutsider", 17}
*/
fmt.Println(peo) //&{theoutsider 17}
}
结构体指针的判断
- 结构体指针比较的是地址
- (*结构体指针)取出地址中对应的值
type People struct {
Name string
Age int
}
func main() {
peo := &People{"theoutsider", 17}
peo2 := &People{"theoutsider", 17}
fmt.Printf("%p %p \n", peo, peo2) //输出:0xc000004480 0xc0000044a0
fmt.Println(peo == peo2) //false
}