Go in Practice, Second Edition cover
welcome to this free extract from
an online version of the Manning book.
to read more
or

13 Reflection, code generation, and advanced Go

 

This chapter covers

  • Using values, kinds, and types from Go’s type reflection system
  • Parsing custom struct annotations
  • Working with other languages via C/C++ interoperability
  • Writing code generators for use with the go generate tool

In chapter 12, we explored using Go in the context of tooling around deployment, looking at service communication and discovery. In this chapter, we turn our attention to some of Go’s most interesting advanced features. We’ll begin with Go’s reflection system, which refers to a program’s runtime ability to examine its own structure. Although Go’s reflection subsystem isn’t as versatile as Java’s, it’s still powerful.

Another feature that has enjoyed novel use is the annotation of structs. You’ll see in the second part of the chapter how to write custom tags for struct fields. As useful as Go’s reflection system is, though, it’s sometimes cleaner to avoid complex and expensive runtime reflection and instead write code that itself writes code; this will be the third focus of the chapter. Finally, although Go now has generics, code generation has a niche role in developing in Go, and we will look at that in comparison with generics.

13.1 Three features of reflection

13.1.1 Switching based on type and kind

13.1.2 Discovering whether a value implements an interface

13.1.3 Accessing fields on a struct

13.2 Structs, tags, and annotations

13.2.1 Annotating structs

13.2.2 Using tag annotations

13.2.3 Processing tags on a struct

13.3 Generating Go code with Go code

13.4 Working with other languages

Summary