有没有一种通用的方式来表示一组相似的函数?

huangapple go评论127阅读模式
英文:

Is there a way to generically represent a group of similar functions?

问题

根据上面的代码,有没有一种方法可以使用映射或数组来收集一组类似的函数adoptXxx?如果没有,对于这种情况,应该使用什么样的模式?

在这种情况下,可以使用映射来收集一组类似的函数。但是,在使用映射之前,需要先对映射进行初始化。你可以使用以下代码来初始化映射:

  1. var adoptFuncs = make(map[string]AdoptFunc)

然后,你可以将函数添加到映射中,例如:

  1. adoptFuncs["dog"] = adoptDog
  2. adoptFuncs["cat"] = adoptCat

这样,你就可以通过映射来调用相应的函数,例如:

  1. adoptFuncs["dog"](Dog(1))
  2. adoptFuncs["cat"](Cat(1))

这样做可以根据不同的键调用不同的函数。希望这可以帮助到你!

英文:
  1. package main
  2. import "fmt"
  3. type Pet interface {
  4. Bark()
  5. }
  6. type Dog int
  7. func (d Dog) Bark() {
  8. fmt.Println("W! W! W!")
  9. }
  10. type Cat int
  11. func (c Cat) Bark() {
  12. fmt.Println("M! M! M!")
  13. }
  14. type AdoptFunc func(pet Pet)
  15. func adoptDog(dog Dog) {
  16. fmt.Println("You live in my house from now on!")
  17. }
  18. func adoptCat(cat Cat) {
  19. fmt.Println("You live in my house from now on!")
  20. }
  21. func main() {
  22. var adoptFuncs map[string]AdoptFunc
  23. adoptFuncs["dog"] = adoptDog // cannot use adoptDog (type func(Dog)) as type AdoptFunc in assignment
  24. adoptFuncs["cat"] = adoptCat // the same as above
  25. }

As the code above, is there a way to use a map or array to collect a bunch of similar functions adoptXxx? If not, what is right pattern to use for this situation?

答案1

得分: 2

要将地图用作函数集合,您需要更改函数的签名以匹配。func(Pet)func(Dog)不是相同的类型。

您可以重写AdoptXXX函数以接受Pet并进行类型选择以确保输入正确的宠物:

  1. func adoptDog(pet Pet) {
  2. if _, ok := pet.(Dog); !ok {
  3. // 处理不正确的宠物类型
  4. }
  5. fmt.Println("从现在开始你住在我的房子里!")
  6. }
英文:

To use the map as a function collection you'll have to change the signature of your functions to match. func(Pet) is not the same type as func(Dog).

You can re-write AdoptXXX functions to take in Pet and do a type select to ensure correct pet is being input:

  1. func adoptDog(pet Pet) {
  2. if _, ok := pet.(Dog); !ok {
  3. // process incorrect pet type
  4. }
  5. fmt.Println("You live in my house from now on!")
  6. }

huangapple
  • 本文由 发表于 2016年8月23日 15:47:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/39095299.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定