0

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 !

2
  • 1
    Did you try it? Did it work? If not: What did the compiler tell you? Commented Nov 29, 2016 at 13:44
  • Problem solved. The program terminated with a runtime error because of a nil pointer dereference. Therefore I have concluded that the passing of the function is wrong but the error was an assignment in a non-pointer method receiver before that. Sorry for your waste of time. :forgiveme: Commented Nov 29, 2016 at 15:04

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

What you've written appears to be correct.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.