douluo5937 2018-06-06 14:55
浏览 45
已采纳

在运行时使用反射创建切片实例

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)

        .....
    }
  • 写回答

1条回答 默认 最新

  • doudang4857 2018-06-06 15:20
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。