Chapter 11. Reflection and code generation

 

This chapter covers

  • Using values, kinds, and types from Go’s reflection system
  • Parsing custom struct annotations
  • Writing code generators for use with the go generate tool

In this chapter, we turn our attention to some of Go’s most interesting features. First, we present Go’s reflection system. Reflection, in software development, refers to a program’s ability to examine its own structure. Although Go’s reflection subsystem isn’t as versatile as Java’s, it’s still powerful. One feature that has enjoyed novel use is the annotation of structs. You’ll see in this chapter how to write custom tags for struct fields. As useful as Go’s reflection system is, though, sometimes it’s cleaner to avoid complex and expensive runtime reflection, and instead write code that writes code. Code generation can accomplish some of the things that are typically done in other languages with generics. That practice, called metaprogramming, is the last thing you’ll look at in this chapter.

11.1. Three features of reflection

Software developers use reflection to examine objects during runtime. In a strongly typed language like Go, you may want to find out whether a particular object satisfies an interface. Or discover what its underlying kind is. Or walk over its fields and modify the data.

11.2. Structs, tags, and annotations

 
 
 
 

11.3. Generating Go code with Go code

 

11.4. Summary

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest