如何實(shí)現(xiàn)golang語(yǔ)言的多態(tài)?
C++里面有多態(tài)是其三大特性之一,那么golang里面的多態(tài)我們?cè)撛趺磳?shí)現(xiàn)?
golang里面有一個(gè)接口類型interface,任何類型只要實(shí)現(xiàn)了接口類型,都可以賦值,如果接口類型是空,那么所有的類型都實(shí)現(xiàn)了它。因?yàn)槭强章铩?/p>
golang里面的多態(tài)就是用接口類型實(shí)現(xiàn)的,即定義一個(gè)接口類型,里面聲明一些要實(shí)現(xiàn)的功能,注意,只要聲明,不要實(shí)現(xiàn),
例如:type People interface { // 只聲明 GetAge() int GetName() string }
然后你就可以定義你的結(jié)構(gòu)體去實(shí)現(xiàn)里面聲明的函數(shù),你的結(jié)構(gòu)體對(duì)象,就可以賦值到該接口類型了。
寫(xiě)了一個(gè)測(cè)試程序:
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() { // 實(shí)現(xiàn)抽象方法1 fmt.Printf("Man[%s, %d] sayhin", this.name, this.age) } func (this *Monster) sayhi() { // 實(shí)現(xiàn)抽象方法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) }
運(yùn)行結(jié)果:
Man[我是人, 100] sayhi
Monster[妖怪, 1000] sayhi