go-generate
Generate Go source code
TLDR
Generate Go files by running commands within source files
SYNOPSIS
go generate [-run regexp] [-n] [-x] [build flags] [packages]
PARAMETERS
-run regexp
execute only commands matching the regular expression
-n
print commands that would run, but do not execute them (dry run)
-x
print each command as it is executed
[build flags]
accepts all flags from go build, like -p for parallelism
[packages]
generate for specified packages; defaults to current directory and subpackages
DESCRIPTION
The go generate command automates code generation in Go projects by executing directives specified in //go:generate comments within .go source files. These directives allow developers to embed commands like generating parsers, protocol buffers, or string methods, ensuring generated code is rebuilt consistently across environments.
It recursively scans the current package and subpackages for directives, executes them in the respective package directories using the system's shell, and supports filtering via regular expressions. This is crucial for maintaining boilerplate-free source code while handling complex generation tasks.
Common uses include tools like stringer, protoc, or custom generators. Run it during development or as a pre-build step to regenerate code automatically, reducing errors from manual processes. It integrates seamlessly with go build and other Go tools.
CAVEATS
Commands execute via shell in package directories; risky with untrusted code due to arbitrary execution. Does not track dependencies automatically; rerun after source changes.
DIRECTIVE FORMAT
//go:generate command [args]
Must be a full line comment; multiple per file allowed; trimmed of leading/trailing space.
USAGE EXAMPLE
//go:generate go install github.com/golang/example/stringer
//go:generate stringer -type=Animal
Then: go generate
HISTORY
Introduced in Go 1.4 (December 2014) to standardize code generation, replacing ad-hoc scripts; enhanced in later versions with better parallelism and flag support.
SEE ALSO
go-build(1), go-fmt(1), go-install(1)


