作者:mobiledu2502855653 | 来源:互联网 | 2023-05-19 18:53
如何实现golang语言的多态?C++里面有多态是其三大特性之一,那么golang里面的多态我们该怎么实现?golang里面有一个接口类型interface,任何类型只要实现了接口
本文摘自php中文网,作者WJ,侵删。
![](https://img.php1.cn/3cd4a/1eebe/cd5/3e641eb5f5c8cd90.webp)
如何实现golang语言的多态?
C++里面有多态是其三大特性之一,那么golang里面的多态我们该怎么实现?
golang里面有一个接口类型interface,任何类型只要实现了接口类型,都可以赋值,如果接口类型是空,那么所有的类型都实现了它。因为是空嘛。
golang里面的多态就是用接口类型实现的,即定义一个接口类型,里面声明一些要实现的功能,注意,只要声明,不要实现,
1 2 3 4 5 | 例如:type People interface {
GetAge() int
GetName() string
}
|
然后你就可以定义你的结构体去实现里面声明的函数,你的结构体对象,就可以赋值到该接口类型了。
写了一个测试程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | package main
import (
"fmt"
)
type Biology interface {
sayhi()
}
type Man struct {
name string
age int
}
type Monster struct {
name string
age int
}
func (this *Man) sayhi() {
fmt.Printf( "Man[%s, %d] sayhi\n" , this.name, this.age)
}
func (this *Monster) sayhi() {
fmt.Printf( "Monster[%s, %d] sayhi\n" , 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