dounao5856 2016-01-05 06:23
浏览 79
已采纳

golang如何实现反射?

Using reflection, we can get the type name, storage size and the function of the given type(such as uint64, user-defined struct and so on). Even, we can modify some fields of the given type. How does golang implement reflections? I guess the following ways:

  1. Every type in golang, including user-defined type, itself has the information about type name, fields name and the function name. Golang reflection just reads these information or call the function.

  2. Through some mechanism, Golang can get the type name, storage size and so on. And the type itself doesn’t have these information.

I have read the golang reflection code roughly. I guessed that golang used the second way. Who can describe the concrete implement of reflection? Or recommend me some documents? Reading all code is difficult for me.

  • 写回答

2条回答 默认 最新

  • dongyuan7110 2016-01-05 09:56
    关注

    This is just an overview and it might be not 100% accurate but hopefully you will find it helpful.

    At build time Go linker will embed information about all types used by the application into the executable (https://github.com/golang/go/blob/master/src/runtime/symtab.go#L39)

    Each interface value contains a pointer to the data type descriptor (https://github.com/golang/go/blob/master/src/runtime/type.go#L14)

    During conversion from a type that is known at compile time to an interface value Go compiler will point type descriptor of this interface value to the concrete type descriptor (it is known at compile time!).

    E.g. when you call reflect.TypeOf(uint(87)):

    • an interface value is created by the compiler that references uint type descriptor
    • this interface value is passed to reflect.TypeOf function as argument
    • reflect.TypeOf function uses type descriptor that has been stored by the linker in the executable to get the align (and other) information about uint type.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大