自动创建结构实例

I am running a piece of code that receives a JSON through MQTT. Every time I receive a JSON (the MQTT is always running), I want to create an instance of a struct that I have. I also want to append that instance to a list to keep track of the number of instances I have.

Here is what I have so far:

func VirtualDevice(client MQTT.Client, deviceID string) **VirtualDevice {
    type Device struct{
        Type        string `json:"type"`
        Value       []interface{} `json:"value"`
        CaptureTime string   `json:"capture-time"`
    }
    type VirtualDevice 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"`
    }

    sensorData := new(VirtualDevice)

    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
", sensorData) //data_update    
        }
    }
    client.Subscribe("data-update/" + deviceID, 0, g)
    return &sensorData //Error: Cannot use &sensorData (type **VirtualDevice) as type **VirtualDevice
}

In another file, I have this:

type Ctrl struct {
    Instance []*VD
}   
var device *VD
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])

As you can see, I cannot return &sensor even though it is type **VirtualDevice. How can I return this and am I on the right track with what I want to achieve? (Create new instances of the same struct with each incoming JSON, and append a pointer to each instances to not lose data)

Edit: I am able to return the struct successfully, but when I print out *sensorList.Instance[0] I get an empty JSON. What am I doing wrong?

Your function can't return a **VirtualDevice because the type is scoped to the function. Move the type definitions outside of the func. If they are already defined outside, just remove them.

Also, I think you might be a bit confused about pointers. new(VirtualDevice) returns a pointer to a newly created VirtualDevice, (so your sensorData is type *VirtualDevice). When you take &sensorData you are getting a pointer of that pointer. You don't often want to do that. You can leave the & off of passing it to json.Unmarshal and the return and change the return type.