3 回答
TA贡献1818条经验 获得超11个赞
您可以使用类型断言:
pr := rows.(ProductResponse)
fmt.Println(pr.CompanyProducts[0].Product_ID)
fmt.Println(pr.CompanyProducts[0].Product_Name)
或者您可以使用反射包:
rv := reflect.ValueOf(rows)
// get the value of the CompanyProducts field
v := rv.FieldByName("CompanyProducts")
// that value is a slice, so use .Index(N) to get the Nth element in that slice
v = v.Index(0)
// the elements are of type *Product so use .Elem() to dereference the pointer and get the struct value
v = v.Elem()
fmt.Println(v.FieldByName("Product_ID").Interface())
fmt.Println(v.FieldByName("Product_Name").Interface())
https://play.golang.org/p/RAcCwj843nM
TA贡献1779条经验 获得超6个赞
您应该使用类型断言,而不是使用反射。
res, ok := response.(ProductResponse)
if ok { // Successful
res.CompanyProducts[0].Product_Name // Access Product_Name or Product_ID
} else {
// Handle type assertion failure
}
TA贡献2080条经验 获得超4个赞
您甚至可以通过使用循环简单地迭代切片来访问值,而无需使用“反射”pkg。我为您创建了一个简单的程序,如下所示:Product_NameCompanyProductsfor
package main
import (
"fmt"
)
type ProductResponse struct {
CompanyName string `json:"company_name"`
CompanyID uint `json:"company_id"`
CompanyProducts []*Products `json:"CompanyProducts"`
}
type Products struct {
Product_ID uint `json:"id"`
Product_Name string `json:"product_name"`
}
func main() {
var rows2 interface{} = ProductResponse{CompanyName: "Zensar", CompanyID: 1001, CompanyProducts: []*Products{{1, "prod1"}, {2, "prod2"}, {3, "prod3"}}}
for i := 0; i < len(rows2.(ProductResponse).CompanyProducts); i++ {
fmt.Println(rows2.(ProductResponse).CompanyProducts[i].Product_Name)
}
}
输出:
prod1
prod2
prod3
- 3 回答
- 0 关注
- 82 浏览
添加回答
举报