October 2015
Beginner to intermediate
400 pages
14h 44m
English
Sometimes we need to write a function capable of dealing uniformly with values of types that don’t satisfy a common interface, don’t have a known representation, or don’t exist at the time we design the function—or even all three.
A familiar example is the formatting
logic within fmt.Fprintf, which can usefully print an arbitrary
value of any type, even a user-defined one. Let’s try to implement a
function like it using what we know already.
For simplicity, our function will accept one argument and will return
the result as a string like fmt.Sprint does, so we’ll call it
Sprint.
We start with a type switch that tests whether the argument defines
a String method, and call it if so.
We then add switch cases that test ...