使用反射访问结构中的结构字段

Using reflect to access struct field within a struct

我有以下内容:

package main

import (
    "fmt"
    "reflect"
)

type Model struct {
    A AStruct  `br:"peg"`
}

type AStruct struct {
    ID string
}

type IModel interface {
}

func main() {
    m := Model{AStruct{ID:"123"}}
    var i IModel;
    i = m
    
    v := reflect.Indirect(reflect.ValueOf(m))
    for i := 0; i < v.NumField(); i++ {
        tag := v.Type().Field(i).Tag.Get("br")
        if tag == "peg" {
            fieldVal := v.Field(i)
            fmt.Println("fieldVal.Kind():", fieldVal.Kind())

            // How do I get it to work with FieldByName("ID") and print 123 once I know the tag has a value "peg"?
        }
    }

    
    fmt.Println("i is", i)
}

我想使用 reflect 打印“123”,但我无法使用。

编辑:

我实际上是在循环查找特定标签。所以我不想做 v.FieldByName("A") directly. But I can do FieldByName("ID") once I get a handle of A`.

The go playground

编辑 2: 更改代码以包含标记。

简单

fmt.Println("field value", v.FieldByName("A").FieldByName("ID"))

可以,在 Go Playground 上试试。

v 是一个 reflect.Value 包装类型 Model 的值,它有一个结构字段 A,它有一个结构字段 ID.

编辑:

如果您想按标签查找字段,请参阅此答案:What are the use(s) for tags in Go?

对于您问题中的代码,现在看起来像:

v := reflect.Indirect(reflect.ValueOf(i))
t := v.Type()
for i := 0; i < v.NumField(); i++ {
    fieldVal := v.Field(i)
    fmt.Println("fieldVal.Kind():", fieldVal.Kind())
    if t.Field(i).Tag.Get("br") == "peg" {
        fmt.Println("\thas tag: gr=peg")
        fmt.Printf("\tfield value: %+v\n", fieldVal)
        fmt.Println("\tID field value:", fieldVal.FieldByName("ID"))
    }
}

输出(在 Go Playground 上尝试):

fieldVal.Kind(): struct
    has tag: gr=peg
    field value: {ID:123}
    ID field value: 123