12.1 Why Reflection?
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access