小编典典

使用反射获取结构字段的名称

go

这里打印“Foo”的方式是什么?在这个例子中,打印的是“字符串”。

http://play.golang.org/p/ZnK6PRwEPp

type A struct {
    Foo string
}

func (a *A) PrintFoo() {
    fmt.Println("Foo value is " + a.Foo)
}

func main() {
    a := &A{Foo: "afoo"}
    val := reflect.Indirect(reflect.ValueOf(a))
    fmt.Println(val.Field(0).Type().Name())
}

阅读 162

收藏
2021-12-25

共1个答案

小编典典

你要val.Type().Field(0).Name。该Field方法对reflect.Type将返回描述该字段,该字段包括名称,以及其它的信息的结构。

无法检索reflect.Value表示特定字段值的字段名称,因为这是包含结构的属性。

2021-12-25