Golang结构体
结构体是由一系列具有相同类型或不同类型的数据构成的数据集合
在golang结构体可以为不同项定义不同的数据类型
1.结构体格式:
type struct_variable_type struct {
member definition
member definition
...
member definition
}
2.变量声明:
variable_name := structure_variable_type {value1, value2...valuen}
或
variable_name := structure_variable_type { key1: value1, key2: value2..., keyn: valuen}
代码示例:
package main
import "fmt"
//结构体定义
type Student struct{
name string
age int
height int
}
func main() {
// 创建一个新的结构体
x1 :=Student{"Tom",18,182}
fmt.Println(x1)
//可以用key:value形式
x2 :=Student{name:"Bob",age:14,height:152}
fmt.Println(x2)
//没有定义的字段为“空值”
x3 :=Student{}
fmt.Println(x3)
}
运行结果为:
{Tom 18 182}
{Bob 14 152}
{ 0 0}
访问结构体成员
结构体.成员名称
不仅可以访问结构体成员,还可以重新赋值
package main
import "fmt"
//结构体定义
type Student struct{
name string
age int
height int
}
func main() {
// 创建一个新的结构体
x1 :=Student{"Tom",18,182}
fmt.Println(x1)
fmt.Println(x1.name)
fmt.Println(x1.age)
fmt.Println(x1.height)
x1.name="Bob"
x1.age=22
x1.height=176
fmt.Println("After change!")
fmt.Println(x1)
fmt.Println(x1.name)
fmt.Println(x1.age)
fmt.Println(x1.height)
}
运行结果为:
{Tom 18 182}
Tom
18
182
After change!
{Bob 22 176}
Bob
22
176
结构体作为函数参数
像其他数据类型一样,将结构体类型作为参数传递给函数,访问它的成员
package main
import "fmt"
//结构体定义
type Student struct{
name string
age int
height int
}
func main() {
var xx Student
xx.name="Lili"
xx.age=17
xx.height=165
showstruct(xx)
}
func showstruct(stu Student){
fmt.Println(stu)
fmt.Println(stu.name)
fmt.Println(stu.age)
fmt.Println(stu.height)
}
运行结果为:
{Lili 17 165}
Lili
17
165
结构体指针
定义指向结构体的指针:
package main
import "fmt"
//结构体定义
type Student struct{
name string
age int
height int
}
func main() {
xx :=Student{"Bob",17,178}
var stu *Student
stu=&xx
fmt.Println(xx)
fmt.Println(*stu)
fmt.Println(stu.name)
fmt.Println(stu.age)
fmt.Println(stu.height)
}
运行结果为:
{Bob 17 178}
{Bob 17 178}
Bob
17
178
结构体指针作为函数参数:
package main
import "fmt"
//结构体定义
type Student struct{
name string
age int
height int
}
func main() {
xx :=Student{"Bob",17,178}
showstruct(&xx)
}
func showstruct(stu *Student){
fmt.Println(*stu)
fmt.Println(stu.name)
fmt.Println(stu.age)
fmt.Println(stu.height)
}
运行结果为:
{Bob 17 178}
Bob
17
178