英文:
How to get the underlying type of the pointer using reflect?
问题
我想要的是通过B
来获取A
的字段,就像这样:
type A struct {
Field_1 string
}
type B struct {
*A
}
fieldsOfA := someMagicFunc(&B{})
英文:
What I want is to get the fields of A
through B
, like
type A struct {
Field_1 string
}
type B struct {
*A
}
fieldsOfA := someMagicFunc(&B{})
答案1
得分: 1
你可以使用reflect.ValueOf()
获取某个变量的Value
反射对象。
如果你还想修改变量或其字段,你需要将变量的地址(指针)传递给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语言中反射的基础知识:
英文:
You can get the Value
reflect object of some variable with reflect.ValueOf()
.
If you also want to modify the variable or its fields, you have to pass the address (pointer) of the variable to ValueOf()
. In this case the Value
will belong to the pointer (not the pointed value), but you can use Value.Elem()
to "navigate" to the Value
of the pointed object.
*A
is embedded in B
, so fields of A
can be referenced from a value of B
. You can simply use Value.FieldByName()
to access a field by name in order to get or set its value.
So this does the work, try it on 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)
Output:
Initial value: {initial}
Field_1 through reflection: initial
After modified through reflection: {works}
I recommend to read this blog post to learn the basics of the reflection in Go:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论