liveBook · Manning

Go:generate directive

As explained in Learn Go with Pocket-Sized Projects

A go:generate directive is a specially formatted Go source comment that specifies a command for go generate to execute.

A go:generate directive is a specially formatted Go source comment that tells go generate to execute the command following //go:generate. It keeps repeatable code-generation commands close to the source they serve. section 10.8 section 10.1.2

Generating gRPC files

Place a directive in generate.go when generating Go and gRPC code from .proto files: //go:generate bash -c "protoc -I=api/proto/ {...} api/proto/*.proto". The shell wrapper matters because go generate does not expand *.proto itself. Run go generate to execute the documented command. section 10.1.2

Use the directive to make generated artifacts reproducible and discoverable:

  • Put generation commands in a generate.go file, a Makefile, or a script where maintainers can find them. section 10.1.2
  • Generate mocks directly from an interface, for example with minimock: //go:generate minimock -i habitCreator -s "_mock.go" -o "mocks". section 10.4.1
  • Run go generate . for one package or go generate ./... for all project generation commands. section 10.4.1
> tree
.
├── api
│   ├── proto
│   │   ├── habit.proto
│   │   └── service.proto
│   ├── generate.go
│   ├── habit.pb.go
│   ├── service_grpc.pb.go
│   └── service.pb.go
├── go.mod
└── go.sum

Inspect the resulting project tree to verify that generate.go and generated Go files appear in the intended directories. section 10.1.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains comment syntax, command placement, shell wildcard limitations, and package-wide invocation, but not command execution internals.
Examples
Uses generate.go for protoc commands and a habitCreator interface for generating minimock test doubles.
What it assumes
Assumes familiarity with Go packages, interfaces, terminals, and external generators while teaching the directive’s syntax and workflow.
What you can do after
Operate/configure reproducible generation by adding directives and running go generate for selected packages or an entire project.
How it connects
Connects code generation with gRPC, Protocol Buffers, protoc, Makefiles, shell commands, interfaces, and mock generation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.