Pass method on struct as callback in golang

huangapple go评论76阅读模式
英文:

Pass method on struct as callback in golang

问题

在Go语言中,可以将结构体的方法作为回调函数传递。在你的示例中,MessageHandler方法可以作为回调函数注册到消息处理器中。

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(){
  //..
  //订阅主题/go-mqtt/sample,并请求以最大的QoS等级0传递消息
  //等待确认订阅的回执信息
              
  if token := c.Subscribe("go-mqtt/sample", 0, mc.MessageHandler); token.Wait() && token.Error() != nil {
                    fmt.Println(token.Error())
                    os.Exit(1)
  }
}

以上代码中,MessageHandler方法被传递给Subscribe函数作为回调函数,用于处理接收到的消息。

英文:

Is it possible to pass a method on a struct as a callback function in golang ?

E.g. Register a message handler :

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

Thank you very much !

答案1

得分: 3

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

英文:

Golang has first class functions, you can pass them as parameters https://golang.org/doc/codewalk/functions/
You may also want to look at this https://dave.cheney.net/2016/11/13/do-not-fear-first-class-functions

答案2

得分: 1

你所写的似乎是正确的。

英文:

What you've written appears to be correct.

huangapple
  • 本文由 发表于 2016年11月29日 21:13:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/40866811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定