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
typeassociated with it. With variablebytes.Buffer, the type isbytes.Buffer. - Kind: Go defines numerous primitive kinds, such as
struct,ptr,int,float64,.... Thereflectpackage enumerates all of the possible kind with the typereflect.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
typenotkind reflect.Valuetype gives you is a group of functions capable of converting related types to their largest representation. A reflect.Value with auint8oruint16can be easily converted to the biggest unsigned integer type by using the reflect.Value โs Uint() method.