LinuxCommandLibrary

go-generate

Generate Go source code

TLDR

Generate Go files by running commands within source files

$ go generate
copy

SYNOPSIS

go generate [-n] [-v] [-x] [build flags] [file.go... | package... | ./...]

PARAMETERS

-n
    Print commands that would be executed, but do not execute them.

-v
    Print the names of generated files.

-x
    Print commands as they are executed.

[build flags]
    Specify build flags to be used during the generate process. These are the standard go build flags.

[file.go... | package... | ./...]
    Specify the files, packages, or directories to process. Defaults to the current directory. ./... will process recursively from the current directory.

DESCRIPTION

The go generate command is a powerful tool for automating repetitive tasks in Go development. It works by scanning Go source files for special comments called directives. These directives specify commands to be executed, often involving code generation tools. The 'go generate' command then executes those commands, creating or modifying Go source code.

It is primarily used for automating tasks such as generating boilerplate code, creating string representations of constants, generating protocol buffer definitions, and generating mocks for testing. The tool encourages organizing code generation logic within the Go source files themselves, making it easy to keep the generation process aligned with the code it generates. By using 'go generate', developers can reduce manual effort and maintain code consistency across projects, simplifying maintenance and improving developer productivity.

CAVEATS

The 'go generate' command executes commands in the shell, so care should be taken to avoid security vulnerabilities when using external tools or untrusted inputs. Commands must be idempotent since they may be run multiple times.

DIRECTIVES

A 'go generate' directive is a special comment in a Go source file that starts with '//go:generate'. The rest of the comment contains the command to be executed. The tools must be available in the PATH.
For example: //go:generate stringer -type=Pill will generate the string method for a enum called Pill.

ENVIRONMENT VARIABLES

The environment variables set when go generate is run include $GOFILE (the name of the file containing the directive), $GOLINE (the line number of the directive), $GOPACKAGE (the package containing the directive), and the standard Go environment variables (e.g., $GOROOT, $GOPATH). These can be used to parameterize the generated code.

HISTORY

The `go generate` command was introduced in Go 1.4 as a means of automating code generation as part of the Go build process. It arose from the need to reduce manual boilerplate coding and facilitate tasks like stringer or mock generation within Go projects.

Copied to clipboard