Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
    } 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading