Reflection

Reflection and code generation

Software developers use reflection to examine objects during runtime.

Switching based on type and kind

  • Type: Each value in Go has a particular type associated with it. With variable bytes.Buffer , the type is bytes.Buffer.
  • Kind: Go defines numerous primitive kinds, such as struct, ptr, int, float64,.... The reflect package enumerates all of the possible kind with the type reflect.Kind
  • Reflection: taking a value => inspecting it => contents, type, kind

Example: You want to write a function that takes generic values(interface {}s), and then does something useful with them based on underlying types

  • Type switching operate on type not kind
  • reflect.Value type gives you is a group of functions capable of converting related types to their largest representation. A reflect.Value with a uint8 or uint16 can be easily converted to the biggest unsigned integer type by using the reflect.Value โ€™s Uint() method.
Last updated on