Reflection
Reflection is the mechanism of inspecting code at runtime. Reflection is useful when you do not know or cannot guarantee the type of input for a function. In cases such as this, reflection can be used to inspect the type of the object and manipulate values of objects.
The Go reflect
package gives you features to inspect and manipulate an object at runtime. It can be used not only for basic types such as int
and string
, but for inspecting slices, arrays, and structs as well.
Let's create a simple print()
function to demonstrate how we can use reflection. We define a utility print function called MyPrint()
that can print different types of objects. This is done by having an interface as an input to the function. Then, inside the function, we make use of the reflect
package to alter the behavior according to the type of the input. Consider the following code:
package main import ( Â Â "fmt" Â Â "reflect" ) type Animal struct...