2016-02-26 99 views
3

我試圖將以下Python功能移植到Golang中。 尤其是,如何將函數存儲在切片中,然後調用它們。 我如何在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 

回答

6

這是很容易實際上是:

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") 
} 

遊樂場:http://play.golang.org/p/xuDsdeRQX3

0
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") 
} 

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

1

另外,如果你想要一個更緊密的結構(當然,沒有必要在所有的,在這種情況下):

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

+0

謝謝!非常清楚! – pkothbauer

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

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

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