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
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.
package main
import "fmt"
func main() {
var funcs = []func(){}
funcs = append(funcs, beeper)
funcs = append(funcs, pinger)
for _, f := range funcs {
f()
}
}
func beeper() {
fmt.Println("I'm a beeper")
}
func pinger() {
fmt.Println("I'm a pinger")
}
Alternatively, if you want an even closer structure (admittedly, not needed, at all, in this case):
package main
import "fmt"
type dispatcher struct {
listeners []func()
}
func (d *dispatcher) addListener(f func()) {
d.listeners = append(d.listeners, f)
}
func (d *dispatcher) notify() {
for _, f := range d.listeners {
f()
}
}
func ping() {
fmt.Println("Ping... ping...")
}
func beep() {
fmt.Println("Beep... beep...")
}
func main() {
d := dispatcher{}
d.addListener(ping)
d.addListener(beep)
d.notify()
}
func main(){
var funcSlice []func()
funcSlice = append(funcSlice, f1)
funcSlice = append(funcSlice, f2)
}
func f1(){
fmt.Println("")
}
func f2(){
fmt.Println("")
}
If you use more complexes functions you do this :
func addr(instru, beforeg [4]int) [4]int {
beforeg[instru[3]] = beforeg[instru[1]] + beforeg[instru[2]]
return beforeg
}
func addi(instru, beforeg [4]int) [4]int {
beforeg[instru[3]] = beforeg[instru[1]] + instru[2]
return beforeg
}
func day16Run(isTest bool) {
arrayFunc:= [16]func([4]int, [4]int) [4]int{addr, addi}
// use arrayFunc
}
And if your functions have differnt signatures, use a slice and append as you go, but be careful when calling the functions : Golang - How do you create a slice of functions with different signatures?