Using go:generate

Let’s learn how to use the go:generate command.

We'll cover the following

Although go:generate is not directly connected to testing or profiling, it is a handy and advanced Go feature, and we believe that this chapter is the perfect place for discussing it because it can also help us with testing. The go:generate directive is associated with the go generate command, was added in Go 1.4 in order to help with automation, and allows us to run commands described by directives within existing files.

The go generate command supports the -v, -n, and -x flags. The -v flag prints the names of packages and files as they are processed, whereas the -n flag prints the commands that would be executed. Lastly, the -x flag prints commands as they are executed—this is great for debugging go:generate commands.

The main reasons that we might need to use go:generate are the following:

  • We want to download dynamic data from the internet or some other source prior to the execution of the Go code.

  • We want to execute some code prior to running the Go code.

  • We want to generate a version number or other unique data before code execution.

  • We want to make sure that we have sample data to work with. For example, we can put data into a database using go:generate.

Note: Because using go:generate is not considered a good practice because it hides things from the developer and creates additional dependencies, we try to avoid it when we can, and we usually can. On the other hand, if we really need it, we are going to know it!

Coding example

The use of go:generate is illustrated in goGenerate.go, which has the following content:

Get hands-on with 1200+ tech skills courses.