Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store functions in a slice in Go

Tags:

python

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
like image 591
pkothbauer Avatar asked Feb 26 '16 09:02

pkothbauer


People also ask

What is the use of Slice in Golang?

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, ...

How do I access a specific slice element in go?

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:

What is a slice type in go?

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.

What are arrays and slices in go?

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.


2 Answers

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.

like image 113
Ainar-G Avatar answered Dec 06 '22 00:12

Ainar-G


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

like image 41
Vatine Avatar answered Dec 06 '22 01:12

Vatine