英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论