-2
是否可以在struct中將方法傳遞爲golang中的回調函數?在golang中將struct方法作爲回調函數傳遞
E.g.註冊消息處理程序:
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)
}
}
非常感謝!
你試過了嗎?它有用嗎?如果不是:編譯器告訴你什麼? – Volker
問題解決了。由於零指針解引用導致程序因運行時錯誤而終止。因此我得出結論認爲,函數的傳遞是錯誤的,但錯誤是之前在非指針方法接收器中的賦值。對不起,浪費時間。 :原諒我: – Aljoscha