如何在Go中将函数存储在切片中

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

How to store functions in a slice in Go

问题

我正在尝试将以下Python功能移植到Golang中。特别是如何将函数存储在切片中并调用它们。在Golang中我该如何做到这一点?

  1. package main
  2. import "fmt"
  3. type Dispatcher struct {
  4. listeners []func()
  5. }
  6. func (d *Dispatcher) addListener(listener func()) {
  7. d.listeners = append(d.listeners, listener)
  8. }
  9. func (d *Dispatcher) notifyUpdate() {
  10. for _, f := range d.listeners {
  11. f()
  12. }
  13. }
  14. func beeper() {
  15. fmt.Println("beep...beep...beep")
  16. }
  17. func pinger() {
  18. fmt.Println("ping...ping...ping")
  19. }
  20. func main() {
  21. dispatch := &Dispatcher{}
  22. dispatch.addListener(beeper)
  23. dispatch.addListener(pinger)
  24. dispatch.notifyUpdate()
  25. }

输出:

  1. beep...beep...beep
  2. ping...ping...ping

以上是将Python代码转换为Golang的示例。在Golang中,我们使用函数类型的切片来存储函数,并通过循环调用它们。

英文:

I'm trying to port the following Python functionality to Golang.
Especially, how to store functions in a slice and then call them.
How can I do this in Golang?

  1. class Dispatcher(object):
  2. def __init__(self):
  3. self._listeners = []
  4. def addlistener(self, listener):
  5. self._listeners.append(listener)
  6. def notifyupdate(self):
  7. for f in self._listeners:
  8. f()
  9. def beeper():
  10. print "beep...beep...beep"
  11. def pinger():
  12. print "ping...ping...ping"
  13. dispatch = Dispatcher()
  14. dispatch.addlistener(beeper)
  15. dispatch.addlistener(pinger)
  16. dispatch.notifyupdate()
  17. output:
  18. beep...beep...beep
  19. ping...ping...ping

答案1

得分: 22

这是一个相当简单的代码:

  1. package main
  2. import "fmt"
  3. func main() {
  4. var fns []func()
  5. fns = append(fns, beeper)
  6. fns = append(fns, pinger)
  7. for _, fn := range fns {
  8. fn()
  9. }
  10. }
  11. func beeper() {
  12. fmt.Println("beep-beep")
  13. }
  14. func pinger() {
  15. fmt.Println("ping-ping")
  16. }

Playground: http://play.golang.org/p/xuDsdeRQX3.

英文:

It's pretty easy actually:

  1. package main
  2. import "fmt"
  3. func main() {
  4. var fns []func()
  5. fns = append(fns, beeper)
  6. fns = append(fns, pinger)
  7. for _, fn := range fns {
  8. fn()
  9. }
  10. }
  11. func beeper() {
  12. fmt.Println("beep-beep")
  13. }
  14. func pinger() {
  15. fmt.Println("ping-ping")
  16. }

Playground: http://play.golang.org/p/xuDsdeRQX3.

答案2

得分: 1

以下是翻译好的内容:

或者,如果你想要一个更接近的结构(诚然,在这种情况下并不需要):

  1. package main
  2. import "fmt"
  3. type dispatcher struct {
  4. listeners []func()
  5. }
  6. func (d *dispatcher) addListener(f func()) {
  7. d.listeners = append(d.listeners, f)
  8. }
  9. func (d *dispatcher) notify() {
  10. for _, f := range d.listeners {
  11. f()
  12. }
  13. }
  14. func ping() {
  15. fmt.Println("Ping... ping...")
  16. }
  17. func beep() {
  18. fmt.Println("Beep... beep...")
  19. }
  20. func main() {
  21. d := dispatcher{}
  22. d.addListener(ping)
  23. d.addListener(beep)
  24. d.notify()
  25. }

Go playground

英文:

Alternatively, if you want an even closer structure (admittedly, not needed, at all, in this case):

  1. package main
  2. import "fmt"
  3. type dispatcher struct {
  4. listeners []func()
  5. }
  6. func (d *dispatcher) addListener(f func()) {
  7. d.listeners = append(d.listeners, f)
  8. }
  9. func (d *dispatcher) notify() {
  10. for _, f := range d.listeners {
  11. f()
  12. }
  13. }
  14. func ping() {
  15. fmt.Println("Ping... ping...")
  16. }
  17. func beep() {
  18. fmt.Println("Beep... beep...")
  19. }
  20. func main() {
  21. d := dispatcher{}
  22. d.addListener(ping)
  23. d.addListener(beep)
  24. d.notify()
  25. }

Go playground

答案3

得分: 0

  1. package main
  2. import "fmt"
  3. func main() {
  4. var funcs = []func(){}
  5. funcs = append(funcs, beeper)
  6. funcs = append(funcs, pinger)
  7. for _, f := range funcs {
  8. f()
  9. }
  10. }
  11. func beeper() {
  12. fmt.Println("I'm a beeper")
  13. }
  14. func pinger() {
  15. fmt.Println("I'm a pinger")
  16. }

点击此处查看代码。

英文:
  1. package main
  2. import "fmt"
  3. func main() {
  4. var funcs = []func(){}
  5. funcs = append(funcs, beeper)
  6. funcs = append(funcs, pinger)
  7. for _, f := range funcs {
  8. f()
  9. }
  10. }
  11. func beeper() {
  12. fmt.Println("I'm a beeper")
  13. }
  14. func pinger() {
  15. fmt.Println("I'm a pinger")
  16. }

http://play.golang.org/p/PaClU6Ri4n

答案4

得分: 0

func main(){
var funcSlice []func()
funcSlice = append(funcSlice, f1)
funcSlice = append(funcSlice, f2)
}

func f1(){
fmt.Println("")
}

func f2(){
fmt.Println("")
}

英文:
  1. func main(){
  2. var funcSlice []func()
  3. funcSlice = append(funcSlice, f1)
  4. funcSlice = append(funcSlice, f2)
  5. }
  6. func f1(){
  7. fmt.Println("")
  8. }
  9. func f2(){
  10. fmt.Println("")
  11. }

答案5

得分: 0

如果你使用更复杂的函数,你可以这样做:

  1. func addr(instru, beforeg [4]int) [4]int {
  2. beforeg[instru[3]] = beforeg[instru[1]] + beforeg[instru[2]]
  3. return beforeg
  4. }
  5. func addi(instru, beforeg [4]int) [4]int {
  6. beforeg[instru[3]] = beforeg[instru[1]] + instru[2]
  7. return beforeg
  8. }
  9. func day16Run(isTest bool) {
  10. arrayFunc := [16]func([4]int, [4]int) [4]int{addr, addi}
  11. // 使用 arrayFunc
  12. }

如果你的函数具有不同的签名,可以使用切片并在需要时进行追加,但在调用函数时要小心:
https://stackoverflow.com/questions/37314365/golang-how-do-you-create-a-slice-of-functions-with-different-signatures

英文:

If you use more complexes functions you do this :

  1. func addr(instru, beforeg [4]int) [4]int {
  2. beforeg[instru[3]] = beforeg[instru[1]] + beforeg[instru[2]]
  3. return beforeg
  4. }
  5. func addi(instru, beforeg [4]int) [4]int {
  6. beforeg[instru[3]] = beforeg[instru[1]] + instru[2]
  7. return beforeg
  8. }
  9. func day16Run(isTest bool) {
  10. arrayFunc:= [16]func([4]int, [4]int) [4]int{addr, addi}
  11. // use arrayFunc
  12. }

And if your functions have differnt signatures, use a slice and append as you go, but be careful when calling the functions :
https://stackoverflow.com/questions/37314365/golang-how-do-you-create-a-slice-of-functions-with-different-signatures

huangapple
  • 本文由 发表于 2016年2月26日 17:58:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/35648561.html
匿名

发表评论

匿名网友

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

确定