duanlingzei0170 2016-11-29 13:13
浏览 149
已采纳

将结构体上的方法传递为golang中的回调

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
", msg.Topic())
   fmt.Printf("MSG: %s
", 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 !

  • 写回答

2条回答 默认 最新

  • 普通网友 2016-11-29 13:44
    关注

    What you've written appears to be correct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?