go

How to store functions in a slice in Go


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?

class Dispatcher(object):
    def __init__(self):
        self._listeners = []

    def addlistener(self, listener):
        self._listeners.append(listener)

    def notifyupdate(self):
        for f in self._listeners:
            f()

def beeper():
    print "beep...beep...beep"

def pinger():
    print "ping...ping...ping"

dispatch = Dispatcher()
dispatch.addlistener(beeper)
dispatch.addlistener(pinger)
dispatch.notifyupdate()

output:
beep...beep...beep

ping...ping...ping

Solution

  • It's pretty easy actually:

    package main
    
    import "fmt"
    
    func main() {
        var fns []func()
        fns = append(fns, beeper)
        fns = append(fns, pinger)
    
        for _, fn := range fns {
            fn()
        }
    }
    
    func beeper() {
        fmt.Println("beep-beep")
    }
    
    func pinger() {
        fmt.Println("ping-ping")
    }
    

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