访问接口内的结构值

我有一个接口{},它类似于 -


Rows interface{}

在行界面中,我放置产品响应结构。


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价值。如何访问它。我可以使用“反射”pkg 访问外部值(公司名称,公司ID)。


value := reflect.ValueOf(response)

CompanyName := value.FieldByName("CompanyName").Interface().(string)

我无法访问产品结构值。如何做到这一点?


慕哥6287543
浏览 83回答 3
3回答

慕尼黑8549860

您可以使用类型断言: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 fieldv := rv.FieldByName("CompanyProducts")// that value is a slice, so use .Index(N) to get the Nth element in that slicev = v.Index(0)// the elements are of type *Product so use .Elem() to dereference the pointer and get the struct valuev = v.Elem()fmt.Println(v.FieldByName("Product_ID").Interface())fmt.Println(v.FieldByName("Product_Name").Interface())https://play.golang.org/p/RAcCwj843nM

哆啦的时光机

您应该使用类型断言,而不是使用反射。res, ok := response.(ProductResponse) if ok { // Successful   res.CompanyProducts[0].Product_Name // Access Product_Name or Product_ID} else {   // Handle type assertion failure }

犯罪嫌疑人X

您甚至可以通过使用循环简单地迭代切片来访问值,而无需使用“反射”pkg。我为您创建了一个简单的程序,如下所示:Product_NameCompanyProductsforpackage mainimport (&nbsp; &nbsp; "fmt")type ProductResponse struct {&nbsp; &nbsp; CompanyName&nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; &nbsp; `json:"company_name"`&nbsp; &nbsp; CompanyID&nbsp; &nbsp; &nbsp; &nbsp;uint&nbsp; &nbsp; &nbsp; &nbsp; `json:"company_id"`&nbsp; &nbsp; CompanyProducts []*Products `json:"CompanyProducts"`}type Products struct {&nbsp; &nbsp; Product_ID&nbsp; &nbsp;uint&nbsp; &nbsp;`json:"id"`&nbsp; &nbsp; Product_Name string `json:"product_name"`}func main() {&nbsp; &nbsp; var rows2 interface{} = ProductResponse{CompanyName: "Zensar", CompanyID: 1001, CompanyProducts: []*Products{{1, "prod1"}, {2, "prod2"}, {3, "prod3"}}}&nbsp; &nbsp; for i := 0; i < len(rows2.(ProductResponse).CompanyProducts); i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(rows2.(ProductResponse).CompanyProducts[i].Product_Name)&nbsp; &nbsp; }}输出:prod1prod2prod3
打开App,查看更多内容
随时随地看视频慕课网APP