Today I learned why and how to go generate. A small replacement for makefile I already wrote of. But what are the differences? Why use it, and also important- when not to. And a little more technical information you might need.

As part of developing an actual project, you sometimes need to generate files. You know… the ones with # generated file DO NOT EDIT comment on them. one example can be protobuf files, you have the recipe data structure in .proto and you want to convert it to an import-able file type. So you probably do a small makefile like this
proto:
protoc -I=pkg/protos --go_out=pkg/protos pkg/protos*.proto
But then time flies and the makefile becomes big and complex, nobody knows what or why it is needed and which resources are using it.
This is when go generate comes to solve- to help you generate utilities for your project in an easy way. Lets say you have a webserver using gRPC and you need protobuf to generate the methods and data types. You can add this code bloc to your server implementation file:
//go:generate protoc -I=pkg/protos --go_out=pkg/protos pkg/protos*.proto
and whenever you want to rebuild the .pb.go file you can simply run go generate ./... and it will run it. here are some few more tips and good-to knows:
- the
go:generatecomment should be at the beginning of the file and can run any single bash command - yes, this is also include
go runcommand. you can write you utilities as go script go builddoes NOT rungo generatebefore it compiles your code- you cannot run 2 commands in the same
//go:generateclause. but you can write multiple of them and they will be executed one by one

So when to use go generate? well, for the obvious reason- if you have files and utilities that needs to be generated. protobufs, automatic code generation like handlers, and non-go depandencies. This can also be a good usage for other cases if you run a small go project that doesn’t have a makefile
When not? if you already have A makefile. if you have a complex usecases that needs to delete stuff and validate things and use variable… you know, the reson you whould use a makefile. But even when you do, sometimes breaking little tasks to go generate can help you document it better.
Further reading:
Generating code – from go.dev blog