[英]Create instance of slice using reflection at run time
我试图传递结构片段,即[]carDetail
或[]bikeDetail
,它们在func fetch(url string, itemList []IMapping) (error)
实现IMapping
接口。 但是随后碰到了这个链接 。 GoLang不支持它。 因此,将签名更改为func fetch(url string, itemList IMapping) (error)
。 现在,我试图在函数中传递carDetail
或bikeDetail
结构,并在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)
.....
}
声明fetch
以采用interface {}参数:
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函数完成了所有繁重的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.