CodeNebula
Go🚀Advancedadvanced

go:generate — Code Generation

Go · Advanced · Run with go run

Explanation

`//go:generate command args` is a directive that `go generate` executes. It runs arbitrary commands — typically to generate code from schemas, mocks, stringer implementations, or protobuf definitions. The generated files are committed to the repo and regenerated when the source changes. Common tools: `stringer`, `mockgen`, `protoc-gen-go`, `sqlc`.

Real-World Scenario

An enum type `Status` with values `Active`, `Inactive`, `Pending` needs a `String()` method for logging. Instead of writing it manually, `//go:generate stringer -type=Status` generates `status_string.go` automatically — update the enum, re-run `go generate`, done.

Quick Snippet

snippet.go
//go:generate stringer -type=Status
//go:generate mockgen -source=service.go -destination=mock_service.go

package main

type Status int

const (
    Active Status = iota
    Inactive
    Pending
)

// After go:generate runs, a status_string.go file is created with:
// func (s Status) String() string { return [Active Inactive Pending][s] }

func main() {
    s := Active
    fmt.Println(s) // Active  (uses generated String() method)
}

Full Example

go_generate.go
// Compile: go run go_generate.go
// Output:
//   status 0 -> Active
//   status 1 -> Inactive
//   status 2 -> Pending
//
// `go generate` runs the //go:generate directives below. In a real
// project, `stringer` would emit a status_string.go file with an
// optimized String() method. Here String() is written by hand to keep
// the example self-contained and runnable.

//go:generate stringer -type=Status

package main

import "fmt"

type Status int

const (
	Active Status = iota
	Inactive
	Pending
)

func (s Status) String() string {
	return [...]string{"Active", "Inactive", "Pending"}[s]
}

func main() {
	for _, s := range []Status{Active, Inactive, Pending} {
		fmt.Printf("status %d -> %s\n", int(s), s)
	}
}
Run command
go run go_generate.go