有没有办法笼统地表示一组相似的功能?

package main


import "fmt"


type Pet interface {

    Bark()

}


type Dog int


func (d Dog) Bark() {

    fmt.Println("W! W! W!")

}


type Cat int


func (c Cat) Bark() {

    fmt.Println("M! M! M!")

}


type AdoptFunc func(pet Pet)


func adoptDog(dog Dog) {

    fmt.Println("You live in my house from now on!")

}

func adoptCat(cat Cat) {

    fmt.Println("You live in my house from now on!")

}


func main() {

    var adoptFuncs map[string]AdoptFunc

    adoptFuncs["dog"] = adoptDog // cannot use adoptDog (type func(Dog)) as type AdoptFunc in assignment

    adoptFuncs["cat"] = adoptCat // the same as above

}

如上代码,有没有办法用map或者array来收集一堆类似的函数adoptXxx?如果不是,那么在这种情况下使用什么正确的模式?


慕沐林林
浏览 165回答 1
1回答

函数式编程

要将地图用作函数集合,您必须更改函数的签名以匹配。func(Pet)不是同一类型func(Dog)。您可以重写AdoptXXX函数以接收Pet并进行类型选择以确保输入正确的宠物:func adoptDog(pet Pet) {    if _, ok := pet.(Dog); !ok {        // process incorrect pet type    }    fmt.Println("You live in my house from now on!")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go