...

/

The reflect Package

The reflect Package

This lesson will help you explore the reflect package more relative to interfaces.

Methods and types in reflect

In the previous chapter, we saw how reflect can be used to analyze a struct. Here, we elaborate further on its powerful possibilities. Reflection in computing is the ability of a program to examine its structure, mainly through the types; it’s a form of meta-programming. The reflect can be used to investigate types and variables at runtime, e.g., their size, and methods, and it can also call these methods dynamically. It can also be useful to work with types from packages of which you do not have the source. It’s a powerful tool that should be used with care and avoided unless strictly necessary.

Basic information of a variable is its type and its value: these are represented in the reflection package by the types Type, which represents a general Go type, and Value, which is the reflection interface to a Go value. Two simple functions, reflect.TypeOf and reflect.ValueOf, retrieve the Type and Value pieces out of any value. For example, if x is defined as:

var x float64 = 3.4

Then, reflect.TypeOf(x) gives float64 and reflect.ValueOf(x) returns 3.4.

Reflection works by examining an interface value; the variable is first converted to the empty interface. This becomes apparent if you look at the signatures of both of these functions:

func TypeOf(i interface{}) Type
func ValueOf(i interface{})
...