
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.