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 variablebytes.Buffer
, the type isbytes.Buffer
. - Kind: Go defines numerous primitive kinds, such as
struct
,ptr
,int
,float64
,.... Thereflect
package 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
type
notkind
reflect.Value
type gives you is a group of functions capable of converting related types to their largest representation. A reflect.Value with auint8
oruint16
can be easily converted to the biggest unsigned integer type by using the reflect.Value โs Uint() method.