Home > Net >  How to access a variable that I can't pass to function
How to access a variable that I can't pass to function

Time:08-13

So I use paho.mqtt to recieve MQTT messages, the received messages are printed like this

var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
    fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
} 

if I now need to access (from that function) for example c that is initialized in main how do I do that?

opts.SetDefaultPublishHandler(messagePubHandler)
opts.OnConnect = connectHandler
opts.OnConnectionLost = connectLostHandler
client := mqtt.NewClient(opts)
d := net.Dialer{Timeout: 5000*time.Millisecond}
c, err := d.Dial("tcp", "127.0.0.1:1234")

I looked at pointers but that doesn't seem to work (or I just don't understand how) and I don't see how I can pass c

CodePudding user response:

Provide a way for c to be in scope.

One example is to move it to a package level variable:

var c mqtt.Client

func main() {
    // ...
    var err error
    c, err = d.Dial("tcp", "127.0.0.1:1234")
}

Then you can refer to c.

Another solution is to initialize messagePubHandler with a closure from main():

var messagePubHandler mqtt.MessageHandler

func main() {
    opts.SetDefaultPublishHandler(messagePubHandler)
    opts.OnConnect = connectHandler
    opts.OnConnectionLost = connectLostHandler
    client := mqtt.NewClient(opts)
    d := net.Dialer{Timeout: 5000*time.Millisecond}
    c, err := d.Dial("tcp", "127.0.0.1:1234")

    messagePubHandler = func(client mqtt.Client, msg mqtt.Message) {
        fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
        // Here you can access c
    } 
}
  •  Tags:  
  • go
  • Related