英文:
How to access a variable that I can't pass to function
问题
所以我使用paho.mqtt来接收MQTT消息,接收到的消息会像这样打印出来:
var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
}
如果我现在需要在这个函数中访问例如在main函数中初始化的变量c,我该如何做呢?
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")
我查看了指针,但似乎不起作用(或者我只是不理解如何使用),而且我不知道如何传递变量c。
英文:
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
答案1
得分: 2
提供一种使c
在作用域内的方法。
一个例子是将其移动到包级别的变量中:
var c mqtt.Client
func main() {
// ...
var err error
c, err = d.Dial("tcp", "127.0.0.1:1234")
}
然后你可以引用c
。
另一种解决方案是使用main()
中的闭包初始化messagePubHandler
:
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())
// 在这里你可以访问c
}
}
英文:
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论