一、struct简介
go语言中没有像类的概念,但是可以通过结构体struct实现oop(面向对象编程)。struct的成员(也叫属性或字段)可以是任何类型,如普通类型、复合类型、函数、map、interface、struct等,所以我们可以理解为go语言中的“类”。
二、struct详解
struct定义
在定义struct成员时候区分大小写,若首字母大写则该成员为公有成员(对外可见),否则是私有成员(对外不可见)。
type struct_variable_type struct { member member_type member member_type ..... member member_type } //示例 type Student struct { name string age int Class string }
声明与初始化
var stu1 Student var stu2 *Student= &Student{} //简写stu2 := &Student{} var stu3 *Student = new(Student) //简写stu3 := new(Student)
struct使用
在struct中,无论使用的是指针的方式声明还是普通方式,访问其成员都使用".",在访问的时候编译器会自动把 stu2.name 转为 (*stu2).name。
struct分配内存使用new,返回的是指针。
struct没有构造函数,但是我们可以自己定义“构造函数”。
struct是我们自己定义的类型,不能和其他类型进行强制转换。
package main import "fmt" type Student struct { name string age int Class string } func main() { var stu1 Student stu1.age = 22 stu1.name = "wd" stu1.Class = "class1" fmt.Println(stu1.name) //wd var stu2 *Student = new(Student) stu2.name = "jack" stu2.age = 33 fmt.Println(stu2.name,(*stu2).name)//jack jack var stu3 *Student = &Student{ name:"rose",age:18,Class:"class3"} fmt.Println(stu3.name,(*stu3).name) //rose rose }
自定义构造函数
以下是通过工厂模式自定义构造函数方法
package main import "fmt" type Student struct { name string age int Class string } func Newstu(name1 string,age1 int,class1 string) *Student { return &Student{name:name1,age:age1,Class:class1} } func main() { stu1 := Newstu("wd",22,"math") fmt.Println(stu1.name) // wd }
tag
tag可以为结构体的成员添加说明或者标签便于使用,这些说明可以通过反射获取到。
在前面提到了,结构体中的成员首字母小写对外不可见,但是我们把成员定义为首字母大写这样与外界进行数据交互会带来极大的不便,此时tag带来了解决方法。
type Student struct { Name string "the name of student" Age int "the age of student" Class string "the class of student" }
应用场景示例,json序列化操作:
package main import ( "encoding/json" "fmt" ) type Student struct { Name string `json:"name"` Age int `json:"age"` } func main() { var stu = Student{Name:"wd",Age:22} data,err := json.Marshal(stu) if err != nil{ fmt.Println("json encode failed err:",err) return } fmt.Println(string(data)) //{"name":"wd","age":22} }
匿名成员(字段、属性)
结构体中,每个成员不一定都有名称,也允许字段没有名字,即匿名成员。
匿名成员的一个重要作用,可以用来实现oop中的继承。
同一种类型匿名成员只允许最多存在一个。
当匿名成员是结构体时,且两个结构体中都存在相同字段时,优先选择最近的字段。
package main import "fmt" type Person struct { Name string Age int } type Student struct { score string Age int Person } func main() { var stu = new(Student) stu.Age = 22 //优先选择Student中的Age fmt.Println(stu.Person.Age,stu.Age)// 0,22 }
继承、多继承
当结构体中的成员也是结构体时,该结构体就继承了这个结构体,继承了其所有的方法与属性,当然有多个结构体成员也就是多继承。
访问父结构中属性也使用“.”,但是当子结构体中存在和父结构中的字段相同时候,只能使用:"子结构体.父结构体.字段"访问父结构体中的属性,如上面示例的stu.Person.Age
继承结构体可以使用别名,访问的时候通过别名访问,如下面示例man1.job.Salary:
package main import "fmt" type Person struct { Name string Age int } type Teacher struct { Salary int Classes string } type man struct { sex string job Teacher //别名,继承Teacher Person //继承P