我想要的是通过B
获取A
的字段,如
type A struct {
Field_1 string
}
type B struct {
*A
}
fieldsOfA := someMagicFunc(&B{})
最佳答案
您可以获得Value
用 reflect.ValueOf()
反射(reflect)某个变量的对象.
如果您还想修改变量或其字段,则必须将变量的地址(指针)传递给ValueOf()
。在这种情况下,Value
将属于指针(而不是指向的值),但您可以使用 Value.Elem()
“导航”到所指向对象的Value
。
*A
嵌入在 B
中,因此可以从 B
的值引用 A
的字段。您可以简单地使用 Value.FieldByName()
通过名称访问字段以获取或设置其值。
这样就可以了,试试 Go Playground :
b := B{A: &A{"initial"}}
fmt.Println("Initial value:", *b.A)
v := reflect.ValueOf(&b).Elem()
fmt.Println("Field_1 through reflection:", v.FieldByName("Field_1").String())
v.FieldByName("Field_1").SetString("works")
fmt.Println("After modified through reflection:", *b.A)
输出:
Initial value: {initial}
Field_1 through reflection: initial
After modified through reflection: {works}
我建议阅读这篇博文来了解 Go 中反射的基础知识:
关于pointers - 如何使用reflect获取指针的底层类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28201395/