go - 在 golang 中将结构上的方法作为回调传递

标签 go

是否可以在 golang 中将方法作为回调函数传递给结构体?

例如注册消息处理程序:

func (mc MQTTClient) MessageHandler(client MQTT.Client, msg MQTT.Message) {
   fmt.Printf("TOPIC: %s\n", msg.Topic())
   fmt.Printf("MSG: %s\n", msg.Payload())
}

func (mc MQTTClient) AddMessageHandler(){
  //..
  //subscribe to the topic /go-mqtt/sample and request messages to be delivered
  //at a maximum qos of zero, wait for the receipt to confirm the subscription

  if token := c.Subscribe("go-mqtt/sample", 0, mc.MessageHandler); token.Wait() && token.Error() != nil {
                    fmt.Println(token.Error())
                    os.Exit(1)
  }
}

非常感谢!

最佳答案

Golang 有一流的功能,你可以将它们作为参数传递 https://golang.org/doc/codewalk/functions/ 您可能还想看看这个 https://dave.cheney.net/2016/11/13/do-not-fear-first-class-functions

关于go - 在 golang 中将结构上的方法作为回调传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40866811/

相关文章:

azure - 使用 GoLang 部署 azure 函数

if-statement - "If with a short statement"有什么好处

shell - 流式操作系统/exec.Command

node.js - Golang 中的 Bcrypt 密码散列(与 Node.js 兼容)?

arrays - 在 Golang 中将指针传递给字符串数组

encryption - openpgp golang gpg 库的问题

go - golang的 "range interface"是如何在内部运行的?

unit-testing - 测试基于时间的字段是否有意义? (戈朗)

Go exec.Command(...).Wait() 永远挂起

go - Go 中已声明但未使用的变量