我有一个接口(interface){},类似于 -
Rows interface{}
在 Rows 界面中,我放置了 ProductResponse 结构。
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"`
}
我想访问 Product_Name 值。如何访问这个。 我可以使用“reflect”pkg 访问外部值(CompanyName、CompanyID)。
value := reflect.ValueOf(response)
CompanyName := value.FieldByName("CompanyName").Interface().(string)
我无法访问Products 结构值。如何做到这一点?
最佳答案
您可以使用 type assertion :
pr := rows.(ProductResponse)
fmt.Println(pr.CompanyProducts[0].Product_ID)
fmt.Println(pr.CompanyProducts[0].Product_Name)
或者您可以使用 reflect
包裹:
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())
关于go - 访问接口(interface)内的结构值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68300260/