golang 是面向过程的语言,go 中没有类,单 go 支持面向对象的编程,go 中的 struct 就像其他语言中的类;go 里没有继承,但可以通过组合来实现。
结构体是一种自定义类型,是不同数据的几何体,struct 是值类型,通常用来定义一个抽象的数据对象,比如学生,可以有姓名,年龄,班级的数据构成。
- type Student struct{
- Name string
- Age int
- Class string
- }
- stu := new(Student)
- stu.Name = "Chain"
- stu.Age = 23
- stu.Class = "3-2"
- stu := Student{"Chian", 23, "3-2"}
- stu := Student{Name:"Chain", Age:23, Class:"3-2"}
定义成员方法的格式如下:
- func(变量名结构体类型)函数名(参数列表)(返回类型列表)
例如:
- func(s Student) Display() {
- fmt.Printf("Name=%s, Age=%d, Class=%s\n", s.Name, s.Age, s.Class)
- }
调用的时候直接用实例名点函数名即可例如:
- stu := Student{"Chian", 23, "3-2"}
- stu.Display()
golang 中没有显式的定义字段或函数的访问权限,那么,访问权限是怎么定义的呢?
字段或函数的首字母大写的话,则为 public 权限
字段或函数的首字母小写的话,则为 private 权限
接口是一系列操作的集合,是一种约束。我们可以把它看作与其他对象通讯的协议。任何非接口类型只要拥有某接口的全部方法,就表示它实现了该接口,go 中无需显式的在该类上添加接口声明。
例如:
- package main
- import (
- "fmt"
- )
- func main(){
- var stu IStudent
- stu = &Student{"chain", 23}
- stu.Display()
- fmt.Println(stu.GetName())
- fmt.Println(stu.GetAge())
- }
- type Student struct{
- Name string
- Age int
- }
- func (stu *Student) Display(){
- fmt.Println("i am student")
- }
- func (stu *Student) GetName() string{
- return stu.Name
- }
- func (stu *Student) GetAge() int{
- return stu.Age
- }
- type IStudent interface{
- Display()
- GetName() string
- GetAge() int
- }
[图片上传失败...(image-f37b74-1514188348248)]
学过面向对象的同学应该都知道面向对象的三大特性:封装,继承,多态。
这三大特性在 golang 中如何实现呢?
请看以下 3 个例子
- package main
- import (
- "fmt"
- )
- func main(){
- stu := new(Student)
- stu.SetName("chain")
- fmt.Println(stu.GetName())
- }
- type Student struct{
- name string
- }
- func (stu *Student) SetName(name string){
- stu.name = name
- }
- func (stu *Student) GetName() string{
- return stu.name
- }
[图片上传失败...(image-e4668b-1514188348248)]
- package main
- import (
- "fmt"
- )
- func main(){
- stu := Student{"chain"}
- fmt.Println(stu)
- aStu := AStudent{Student{"chain"}, 23}
- fmt.Println(aStu)
- }
- type Student struct{
- name string
- }
- type AStudent struct{
- Student
- Age int
- }
[图片上传失败...(image-6a9fd1-1514188348248)]
- package main
- import("fmt")
- func main() {
- var stu IStudent stu = &AStudent {}
- stu.Display()
- stu = &BStudent {}
- stu.Display()
- }
- type AStudent struct {
- }
- func(stu * AStudent) Display() {
- fmt.Println("i am a student")
- }
- type BStudent struct {
- }
- func(stu * BStudent) Display() {
- fmt.Println("i am b student")
- }
- type IStudent interface {
- Display()
- }
[图片上传失败...(image-79e86e-1514188348248)]
来源: http://www.jianshu.com/p/d8216baffa27