[英]Appending pointer to a struct slice empty
我有一段代碼可以接收JSON,並根據它的deviceID
創建一個結構實例。
type Ctrl struct {
Instance []*VD
}
var device *VD
if integrationResult == "successful"{
if len(sensorList.Instance) == 0 {
device = VirtualDevice(client, deviceID)
oldDeviceID = deviceID
sensorList.Instance = append(sensorList.Instance, device)
} else if oldDeviceID != deviceID{
device = VirtualDevice(client, deviceID)
sensorList.Instance = append(sensorList.Instance, device)
}
fmt.Println(*sensorList.Instance[0]) //nothing is in here
}
在另一個文件中,我有:
type Device struct{
Type string `json:"type"`
Value []interface{} `json:"value"`
CaptureTime string `json:"capture-time"`
}
type VD struct {
Passport struct {
MessageTopic string `json:"message-topic"`
PrivateKey string `json:"private-key"`
} `json:"passport"`
Data struct {
Sensor []Device `json:"sensor"`
Actuator struct {
} `json:"actuator"`
} `json:"data"`
}
func VirtualDevice(client MQTT.Client, deviceID string) *VD {
sensorData := new(VD)
var g MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
err := json.Unmarshal(msg.Payload(), &sensorData)
if err != nil {
panic(err)
} else {
//fmt.Printf("%+v\n", *sensorData) //data_update
}
}
client.Subscribe("data-update/" + deviceID, 0, g)
return sensorData
}
我遇到的問題是*sensorList.Instance[0]
打印出一個空的JSON。 為什么會這樣呢?
在返回數據之前,您無需等待sensorData
實際被數據填充,因此您將返回一個空結構。 你可以等一下
token := client.Subscribe("data-update/" + deviceID, 0, g)
token.wait()
if token.Error() != nil {
// do something useful here
}
return sensorData
您還可以使用WaitTimeout
來指定時間time.Duration
是放棄之前等待數據的最長時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.