struct结构体:Go语言提供的自定义的数据类型,可以封装多个基本数据类型。
struc结构体定义:
type 结构体名称 struct{
成员名 成员type
…
}
struct结构体实例化:struct结构体只有实例化后,系统才会分配内存。
var 实例化名 struct类型
type Student struct{
name string
age int
score int
}
func main(){
var S student // struct结构体的实例化
S.name = "张三"
S.age = 18
S.score = 90
}
创建指针类型的struct结构体:
type Student struct{
name string
age int
score int
}
func main(){
var P1 new(Student) //使用new实例化一个指针类型结构体
P1.name = "李四"
P1.age = 19
P1.score = 70
}
go语言也支持结构体指针使用 “.”直接访问结构体的成员
构造函数
Go语言没有构造函数的概念,但是可以由我们程序员自己实现构造函数。
构造函数:通过结构体,实现相应功能模板,方便其他函数调用,实现显影功能。
构造函数的命名一般为:new+结构体名称
type persen struct{
name string
age int
city string
}
//构造函数,返回值为一个指针
func newPersen(n string, a int, c string) *P{
return &P{
name : n,
age : a,
city : c,
}
}
func main(){
p1 := newPersen("王五",20,"深圳")//P1为一个指针
}
结构体为值类型,如果结构体比较复杂,值拷贝的成本会很大,所以构造函数返回值一般为指针类型。