这里打印“Foo”的方式是什么?在这个例子中,打印的是“string”。
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())
}
原文由 sat 发布,翻译遵循 CC BY-SA 4.0 许可协议
你想要
val.Type().Field(0).Name
。Field
reflect.Type
的方法将返回描述该字段的结构,其中包括名称和其他信息。无法检索代表特定字段值的
reflect.Value
的字段名称,因为这是包含结构的属性。