A comprehensive guide to go generate

submited by
Style Pass
2021-10-27 03:30:06

Developers have strong tendencies to automate repetitive tasks, and this applies to writing code as well. Therefore, the topic of metaprogramming is a hot area of development and research, and hails back to Lisp in the 1960s. One specific aspect of metaprogramming that has been particularly useful is code-generation, or writing programs that emit other programs, or parts of themselves. Languages that support macros have this capability built-in; other languages extend existing features to support this (e.g. C++ template metaprogramming).

While Go does not have macros or other forms of metaprogramming, it's a pragmatic language and it embraces code generation with support in the official toolchain.

The go generate command has been introduced all the way back in Go 1.4, and since then has been widely used in the Go ecosystem. The Go project itself relies on go generate in dozens of places; I'll do a quick overview of these use cases later on in the post.

It's very important to emphasize that the above is the whole extent of automation Go provides for code generation. For anything else, the developer is free to use whatever workflow works for them. For example, go generate should always be run manually by the developer; it's never invoked automatically (say as part of go build). Moreover, since with Go we typically ship binaries to users or execution environments, it is well understood that go generate is only run during development (likely just before running go build); users of Go programs shouldn't know whether parts of the code are generated and how.

Leave a Comment