简体   繁体   中英

Appending pointer to a struct slice empty

I have a piece of code that receives a JSON and creates a instance of a struct depending on it's 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
}

In another file I have:

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
}

The issue that I have is that *sensorList.Instance[0] prints out an empty JSON. Why is this the case?

You're not waiting for sensorData to actually be filled with data before you return it, so you're returning an empty structure. You can wait for it with

token := client.Subscribe("data-update/" + deviceID, 0, g)
token.wait()
if token.Error() != nil {
    // do something useful here
}
return sensorData

You can also use WaitTimeout which lets you specify a time.Duration which is the maximum time you will wait for the data before giving up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM