liveBook · Manning

Code generation

As explained in Learn Go with Pocket-Sized Projects

Code generation is the automatic production of source or executable code from schemas, specifications, or other input artifacts.

Code generation turns Protobuf message and service definitions into Go source files for a gRPC application. The protoc compiler coordinates language-specific plugins and output paths. section 10.1.2

A practical generation workflow:

  • Install protoc, then install protoc-gen-go and protoc-gen-go-grpc with Go. section 10.1.2
  • Compile .proto files with --go_out, --go-grpc_out, and source_relative path options. section 10.1.2
  • Add -I when files import definitions from another directory, then automate the command with go:generate. section 10.1.2
> protoc -I=api/proto/ --go_out=api/ --go_opt=paths=source_relative 
    --go-grpc_out=api/ --go-grpc_opt=paths=source_relative 
    api/proto/*.proto

Use the complete protoc command to generate both ordinary Go types and gRPC service code from the API definitions. section 10.1.2

Generated project layout

After generation, the api directory contains the original proto files alongside habit.pb.go, service.pb.go, service_grpc.pb.go, and generate.go. section 10.1.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Traces installation, compiler flags, import resolution, output layout, and automation, but stops short of generated-code internals.
Examples
Uses protoc commands, generated habit.pb.go and service files, directory trees, and a go:generate directive.
What it assumes
Assumes a Go module and Protobuf definitions, while teaching compiler installation, plugin setup, flags, and import search paths.
What you can do after
Operate protoc and its Go plugins to generate organized message and gRPC service source files.
How it connects
Connects Protobuf, protoc, Go plugins, gRPC, Go modules, import paths, and source-relative output.

Also explained in

Compare how 17 books explain code 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.