mercredi 6 juin 2018

Create instance of slice using reflection at run time

I was trying to pass the slice of structs i.e. []carDetail or []bikeDetail which implement the IMapping interface in the func fetch(url string, itemList []IMapping) (error). But then came across this link. GoLang doesn't support it. So, changed the signature to be func fetch(url string, itemList IMapping) (error). Now, I am trying to pass the carDetail or bikeDetail struct in the function and in the fetch function trying to create the slice of struct using reflection. So, how can I do that? Which further can be passed in the json.Unmarshal method to map the json to struct.

type IMapping interface {
        GetId() int
    }

    type carDetail struct {
        ModelId    int    `json:"modelId"`
        CarName  string `json:"carName"`
    }
    func (m *carDetail) GetId() int {
        return m.ModelID
    }

    type bikeDetail struct {
        ModelId    int    `json:"modelId"`
        BikeName  string `json:"bikeName"`
    }

    func (m *bikeDetail) GetId() int {
        return m.ModelID
    }

    func fetch(url string, itemList IMapping) (error) {

        var myClient = &http.Client{}
        r, err := myClient.Get(url)
        body, err := ioutil.ReadAll(r.Body)
        defer r.Body.Close()

        // how to create slice at run time using reflection say objVehicle

        err = json.Unmarshal(body, &objVehicle)

        .....
    }





Aucun commentaire:

Enregistrer un commentaire