【问题标题】:Create instance of slice using reflection at run time在运行时使用反射创建切片实例
【发布时间】:2018-06-09 02:54:06
【问题描述】:

我试图传递结构片段,即[]carDetail[]bikeDetail,它们在func fetch(url string, itemList []IMapping) (error) 中实现了IMapping 接口。但后来遇到了这个link。 GoLang 不支持它。因此,将签名更改为func fetch(url string, itemList IMapping) (error)。现在,我试图在函数中传递carDetailbikeDetail 结构,并在fetch 函数中尝试使用反射创建结构切片。那么,我该怎么做呢?进一步可以在json.Unmarshal方法中传递,将json映射到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)

        .....
    }

【问题讨论】:

标签: go reflection


【解决方案1】:

声明fetch 接受接口{} 参数:

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)
    .....
}

使用指向适当类型切片的指针调用它:

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

通过这种方法,json.Umarshal 函数可以完成所有繁重的工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 2018-03-29
    • 2016-04-16
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多