2016-11-29 80 views
-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) 
    } 
} 

非常感谢!

+1

你试过了吗?它有用吗?如果不是:编译器告诉你什么? – Volker

+0

问题解决了。由于零指针解引用导致程序因运行时错误而终止。因此我得出结论认为,函数的传递是错误的,但错误是之前在非指针方法接收器中的赋值。对不起,浪费时间。 :原谅我: – Aljoscha

回答

1

你写什么似乎是正确的。

相关问题