Go的类型-面向对象编程

Go的类型-面向对象编程

1.借助结构体来实现类的声明,比如声明一个学生类,就是创建一个结构体

type Student struct {
    id uint
    name string
    male bool
    score float64
}
func main() {
    stu := Student{1, "张三", true, 123}//实例化
}

2.结构体初始化函数,自定义一个公有函数(就是首字母大写)

func NewStudent (id uint,name string, male bool, score float64) *Student {
    return &Student{id, name, male, score}//返回一个指向结构体实例的指针
}

func main() {
    stu := NewStudent(1,"张三", true, 33)//使用初始化函数来实例化
}

 3.为结构体增加方法

//为Student类型增加方法
func (s Student) getDsc() string{
    return fmt.Sprintf("我的名字叫:%s,得分为:%f", s.name, s.score)
}
//直接传入结构体指针,减少拷贝,可以降低内存消耗
func (s *Student) addScore(score float64) {
    (*s).score = (*s).score+score
}

func main()  {
    stu := NewStudent(1,"张三", true, 33)
    desc1 :=stu.getDsc()
    stu.addScore(5)//会直接在stu实例的score属性加5
    fmt.Println(desc1,desc2)
}

4.结构体的继承-组合

type Animal struct {
    name string
}
func (a Animal) Call() string{
    return "动物的叫声。。。"
}
type Dog struct {
    Animal//写入另外一个类型,则Dog类型继承了Animal的属性和方法
}
func main() {
    animal := Animal{"狗"}
    dog := Dog{animal}
    dog.call()// "动物的叫声。。。"
}

5.方法重写

上面的例子,如果为Dog类型增加一个Call方法,dog.call()就是执行dog类型的call方法。

 6.接口的定义和实现

只要结构体实现了接口的所有方法,就说这个结构体实现了接口

type Animal interface{
    Call()string
    AddNum(num int)
}
---------------------------------
type Dog struct{ 
    number int
}
func (d Dog)Call()string{
    return "汪汪"
}
func (d *Dog)AddNum(num int) {
    (*d).number = (*d).number+num
}

7.接口和类的映射,把类实例指针赋值给接口变量即可,这个接口变量就可以使用定义的方法了。类似于laravel的接口和实现类绑定(通过IOC)

//上面定义的Animal接口,Dog类,可以看出Dog类实现了所有Animal接口的方法
import (
    "animal"
    "fmt"
)
func main()  {
    dog := animal.NewDog("狗", 10)//得到一个类实例指针
    var animal animal.Animal = dog//赋值给接口变量 animal
    animal.Call()//接口变量就可以使用方法了
    fmt.Println(dog,animal)
}

猜你喜欢

转载自blog.csdn.net/littlexiaoshuishui/article/details/105714492