donglugou6652
2016-02-26 09:58
浏览 165
已采纳

如何在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

图片转代码服务由CSDN问答提供 功能建议

我正在尝试将以下Python功能移植到Golang。 尤其是如何在切片中存储函数和 然后打电话给他们。 如何在Golang中做到这一点?

  class Dispatcher(object):
 def __init __(self):
 self._listeners = [] \  n 
 def addlistener(self,listener):
 self._listeners.append(listener)
 
 def notifyupdate(self):
 for self中的f._listeners:
f()
 
def beperper(  ):
打印“ beep ... beep ... beep” 
 
def pinger():
打印“ ping ... ping ... ping” 
 
dispatch = Dispatcher()
dispatch.addlistener  (蜂鸣器)
dispatch.addlistener(声波发射器)
dispatch.notifyupdate()
 
output:\ ... nbeep ...嘟嘟
 
ping ... ...平平
  <  / pre> 
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

5条回答 默认 最新

  • dpi96151 2016-02-26 10:02
    最佳回答

    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.

    评论
    解决 无用
    打赏 举报
查看更多回答(4条)

相关推荐 更多相似问题