0

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)

        .....
    }
Naresh
  • 5,073
  • 12
  • 67
  • 124
  • you can use struct directly without interface and create a slice of struct in your fetch function to unmarshal the data – Himanshu Jun 06 '18 at 14:57
  • Possible duplicate of https://stackoverflow.com/questions/34440646/how-to-create-a-generic-function-to-unmarshal-all-types – Charlie Tumahai Jun 06 '18 at 15:26

1 Answers1

1

Declare fetch to take an interface{} argument:

func fetch(url string, itemList interface{}) (error) {
    var myClient = &http.Client{}
    r, err := myClient.Get(url)
    body, err := ioutil.ReadAll(r.Body)
    defer r.Body.Close()
    err = json.Unmarshal(body, itemList)
    .....
}

Call it with a pointer to a slice of the appropriate type:

var details []carDetail
err := fetch(u, &details)

With this approach, the json.Umarshal function does all the heavy lifting.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242