为了账号安全,请及时绑定邮箱和手机立即绑定

访问接口内的结构值

访问接口内的结构值

Go
慕哥6287543 2022-09-12 20:10:03
我有一个接口{},它类似于 -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)我无法访问产品结构值。如何做到这一点?
查看完整描述

3 回答

?
慕尼黑8549860

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


查看完整回答
反对 回复 2022-09-12
?
哆啦的时光机

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 

}


查看完整回答
反对 回复 2022-09-12
?
犯罪嫌疑人X

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


查看完整回答
反对 回复 2022-09-12
  • 3 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信