如何实现golang语言的多态

2020-08-07 16:53:18

如何实现golang语言的多态?

C++里面有多态是其三大特性之一,那么golang里面的多态我们该怎么实现?

golang里面有一个接口类型interface,任何类型只要实现了接口类型,都可以赋值,如果接口类型是空,那么所有的类型都实现了它。因为是空嘛。

golang里面的多态就是用接口类型实现的,即定义一个接口类型,里面声明一些要实现的功能,注意,只要声明,不要实现,

例如:type People interface {    // 只声明    GetAge() int     GetName() string }

然后你就可以定义你的结构体去实现里面声明的函数,你的结构体对象,就可以赋值到该接口类型了。

写了一个测试程序:

package mainimport (    "fmt")type Biology interface {    sayhi()}type Man struct {    name string    age  int}type Monster struct {    name string    age  int}func (this *Man) sayhi()  { // 实现抽象方法1    fmt.Printf("Man[%s, %d] sayhin", this.name, this.age)}func (this *Monster) sayhi()  { // 实现抽象方法1    fmt.Printf("Monster[%s, %d] sayhin", this.name, this.age)}func WhoSayHi(i Biology) {    i.sayhi()}func main() {    man := &Man{"我是人", 100}    monster := &Monster{"妖怪", 1000}    WhoSayHi(man)    WhoSayHi(monster)}

运行结果:

Man[我是人, 100] sayhi

Monster[妖怪, 1000] sayhi

相关推荐:Golang教程