使用反射(reflect)如何获取指针的底层类型?

huangapple go评论78阅读模式
英文:

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语言中反射的基础知识:

The Laws of Reflection

英文:

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:

The Laws of Reflection

huangapple
  • 本文由 发表于 2015年1月29日 04:06:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/28201395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定