Skip to Content
The Go Programming Language
book

The Go Programming Language

by Alan A. A. Donovan, Brian W. Kernighan
October 2015
Beginner to intermediate
400 pages
14h 44m
English
Addison-Wesley Professional
Content preview from The Go Programming Language

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.
Start your free trial

You might also like

The Rust Programming Language, 2nd Edition

The Rust Programming Language, 2nd Edition

Steve Klabnik, Carol Nichols
Programming Rust, 2nd Edition

Programming Rust, 2nd Edition

Jim Blandy, Jason Orendorff, Leonora F. S. Tindall
Grokking Algorithms

Grokking Algorithms

Aditya Bhargava

Publisher Resources

ISBN: 9780134190570Purchase book