package mainimport "fmt"type Pet interface { Bark()}type Dog intfunc (d Dog) Bark() { fmt.Println("W! W! W!")}type Cat intfunc (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?如果不是,那么在这种情况下使用什么正确的模式?
1 回答
函数式编程
TA贡献1807条经验 获得超9个赞
要将地图用作函数集合,您必须更改函数的签名以匹配。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!")
}
- 1 回答
- 0 关注
- 164 浏览
添加回答
举报
0/150
提交
取消
