如何在Go中的切片中存储函数 [英] How to store functions in a slice in Go

查看:50
本文介绍了如何在Go中的切片中存储函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以下Python功能移植到Golang.特别是,如何将函数存储在切片中然后调用它们.我该如何在Golang中做到这一点?

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

推荐答案

实际上很简单:

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 .

这篇关于如何在Go中的切片中存储函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆