golang裏面的多態怎麼玩?

C++裏面有多態是其三大特性之一,那麼golang裏面的多態我們該怎麼實現?

golang裏面有一個接口類型interface,任何類型只要實現了接口類型,都可以賦值,如果接口類型是空,那麼所有的類型都實現了它。因爲是空嘛。

golang裏面的多態就是用接口類型實現的,即定義一個接口類型,裏面聲明一些要實現的功能,注意,只要聲明,不要實現,

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

然後你就可以定義你的結構體去實現裏面聲明的函數,你的結構體對象,就可以賦值到該接口類型了。

寫了一個測試程序:

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()  { // 實現抽象方法1
    fmt.Printf("Man[%s, %d] sayhi\n", this.name, this.age)
}

func (this *Monster) sayhi()  { // 實現抽象方法1
    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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章