简体   繁体   中英

How to get the underlying type of the pointer using reflect?

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{})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM