aljoshare
aljoshare

Reputation: 802

Pass method on struct as callback in 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\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 !

Upvotes: 0

Views: 4187

Answers (2)

Franck Jeannin
Franck Jeannin

Reputation: 6844

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

Upvotes: 3

Ken Bloom
Ken Bloom

Reputation: 58810

What you've written appears to be correct.

Upvotes: 1

Related Questions