是否可以在 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/