本文探讨了从包含嵌套结构体的接口中获取特定值的方法。接口包含一个名为 `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学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
