有没有一种方法可以通用地表示一组相似的函数?
Is there a way to generically represent a group of similar functions?
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?如果不是,那么在这种情况下使用什么模式才是正确的?
要将地图用作函数集合,您必须更改函数的签名以匹配。 func(Pet)
与 func(Dog)
的类型不同。
您可以重新编写 AdoptXXX
函数以接收 Pet
并输入 select 以确保输入正确的宠物:
func adoptDog(pet Pet) {
if _, ok := pet.(Dog); !ok {
// process incorrect pet type
}
fmt.Println("You live in my house from now on!")
}
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?如果不是,那么在这种情况下使用什么模式才是正确的?
要将地图用作函数集合,您必须更改函数的签名以匹配。 func(Pet)
与 func(Dog)
的类型不同。
您可以重新编写 AdoptXXX
函数以接收 Pet
并输入 select 以确保输入正确的宠物:
func adoptDog(pet Pet) {
if _, ok := pet.(Dog); !ok {
// process incorrect pet type
}
fmt.Println("You live in my house from now on!")
}