go - 访问接口(interface)内的结构值

标签 go struct interface

我有一个接口(interface){},类似于 -

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)

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

最佳答案

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

关于go - 访问接口(interface)内的结构值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68300260/

相关文章:

c# - 使用 C# 调用返回结构数组的非托管 dll 函数

c - 返回指向结构体的指针

c# - 为什么 IComparer 要求您定义 IComparer.Compare(Object x, Object y) 而不仅仅是 Compare(Object x, Object y)?

从 go 调用 C 函数

go - 由于 slice 中的项目数正在变化,如何安全地从 slice 中删除项目

Go语言: Using package name inside package scope (for Examples)

c++ - 使用模板在类(双向链表)中定义结构

Gorm 不创建条目

java - 实现一个java接口(interface)

python - Python中抽象类和接口(interface)的区别