Printf and Reflection

This lesson shows how to modify printing using the reflect package and how to overload a function using an empty interface.

Introduction

The capabilities of the reflection package discussed in the previous section are heavily used in the standard library. For example, the function Printf and so on use it to unpack its … arguments. Printf is declared as:

func Printf(format string, args ... interface{}) (n int, err error)

The … argument inside Printf has the type interface{}, and Printf uses the reflection package to unpack it and discover the argument list. As a result, Printf knows the actual types of their arguments. Because they know if the argument is unsigned or long, there is no %u or %ld, only %d. This is also how Print and Println can print the arguments nicely without a format string.

Explanation

To make this more concrete, we implement a simplified version of such a generic print-function in the following example, which uses a type-switch to deduce the type. According to this, it prints the variable out.

Get hands-on with 1200+ tech skills courses.