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
Slices in Golang. In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, ...
You can access a specific slice element by referring to the index number. In Go, indexes start at 0. That means that [0] is the first element, [1] is the second element, etc. This example shows how to access the first and third elements in the prices slice:
Go’s slice type provides a convenient and efficient means of working with sequences of typed data. Slices are analogous to arrays in other languages, but have some unusual properties. This article will look at what slices are and how they are used.
In Go, arrays and slices are data structures that consist of an ordered sequence of elements. These data collections are great to use when you want to work with many related values. They enable you to keep data together that belongs together, condense your code, and perform the same methods and operations on multiple values at once.
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.
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()
}
Go playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With