Once Upon a Reflection: Looking Deeper into Golang reflection
I often reflect upon my code…
One of the coolest features of the Golang programming language is the reflect package. As the package documentation states at the onset of the package:
Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The typical use is to take a value with static type interface{} and extract its dynamic type information by calling TypeOf, which returns a Type.
On the surface, that all sounds pretty straight-forward. But when you start to think about the types of objects (literally) that you might reflect upon, things can get interesting pretty quickly. It’s one thing to dynamically get the type of an object like an Int
, and then extract it’s value. But what about dynamically getting access to Methods inside a struct
and then calling it with values created dynamically from an a-priori signature, returning values and extracting those values programatically? Rather quickly, the power of reflection can become overwhelming and even confusion. Moreover, appropriate use-cases of reflection should be well thought out so that we aren’t simply
getting too clever for our own good.