登录
首页 >  Golang >  Go问答

获取接口中结构体的值

来源:stackoverflow

时间:2024-03-25 15:06:32 158浏览 收藏

本文探讨了从包含嵌套结构体的接口中获取特定值的方法。接口包含一个名为 `productresponse` 的结构体,其中包含 `companyproducts` 字段,该字段是一个包含 `product` 结构体的切片。可以使用类型断言或 `reflect` 包访问这些嵌套值。

问题内容

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

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)

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


正确答案


您可以使用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())

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 
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>