doupin1073 2015-01-28 20:06
浏览 26

如何使用反射获取指针的基础类型?

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条回答 默认 最新

  • douqiao7958 2015-01-28 20:17
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)