Reflection
We begin this chapter with reflection, which is an advanced Go feature, not because it is an easy subject but because it is going to help you understand how Go works with different data types, including interfaces, and why it is needed.
You might be wondering how you can find out the names of the fields of a structure at execution time. In such cases, you need to use reflection. Apart from enabling you to print the fields and the values of a structure, reflection also allows you to explore and manipulate unknown structures like the ones created from decoding JSON data.
The two main questions that I asked myself when I was introduced to reflection for the first time were the following:
- Why is reflection included in Go?
- When should reflection be used?
To answer the first question, reflection allows you to dynamically learn the type of an arbitrary object along with information about its structure. Go provides the reflect
package for working...