访问接口内的结构值

Abu*_*had 1 struct interface go

我有一个类似的界面{} -

Rows interface{}
Run Code Online (Sandbox Code Playgroud)

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"`
}
Run Code Online (Sandbox Code Playgroud)

我想访问 Product_Name 值。如何访问这个。我可以使用“ reflect ”pkg访问外部值(CompanyName、CompanyID)。

value := reflect.ValueOf(response)
CompanyName := value.FieldByName("CompanyName").Interface().(string)
Run Code Online (Sandbox Code Playgroud)

我无法访问Products结构值。怎么做?

mko*_*iva 5

您可以使用类型断言

pr := rows.(ProductResponse)
fmt.Println(pr.CompanyProducts[0].Product_ID)
fmt.Println(pr.CompanyProducts[0].Product_Name)
Run Code Online (Sandbox Code Playgroud)

或者你可以使用这个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())
Run Code Online (Sandbox Code Playgroud)

https://play.golang.org/p/RAcCwj843nM