Printf and Reflection
Explore how Go's reflection package supports dynamic type handling in functions like Printf. Learn to implement a generic print function using interfaces, type switches, and methods, understanding how Go mimics function overloading and dynamic typing.
We'll cover the following...
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 ...