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

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

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

问题

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

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

var adoptFuncs = make(map[string]AdoptFunc)

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

adoptFuncs["dog"] = adoptDog
adoptFuncs["cat"] = adoptCat

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

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

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

英文:
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
}

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并进行类型选择以确保输入正确的宠物:

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

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:

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

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:

确定