go generate

Purpose: go generate runs code generation tools specified by directives in your source files. It helps automate tasks such as code generation, preprocessing, and running external tools as part of the build process.

Usage:

  1. Add //go:generate Directives in Source Files:

    • Place //go:generate comments in your Go source files to specify the commands that should be run when go generate is executed.
  2. Run go generate ./...:

    • This command scans the package in the current directory and all its subdirectories, executing the specified generation commands.

Example

Step-by-Step Instructions

  1. Create a Go Source File with //go:generate Directive:

    go
    // main.go package main //go:generate go run tools/gen.go import "fmt" func main() { fmt.Println("Hello, Go Generate!") }
    • The //go:generate directive specifies that the echo command and a Go script (tools/gen.go) should be run.
  2. Create the Code Generation Script:

    go
    // tools/gen.go package main import ( "os" ) func main() { f, err := os.Create("generated_code.go") if err != nil { panic(err) } defer f.Close() f.WriteString("// Code generated by gen.go; DO NOT EDIT.\n") f.WriteString("package main\n") f.WriteString("func GeneratedFunction() { fmt.Println(\"This is a generated function.\") }\n") }
    • This script generates a new Go file generated_code.go with a function GeneratedFunction.
  3. Run go generate:

    sh
    go generate ./...
    • This command finds all //go:generate directives in the current package and its subdirectories and executes the specified commands.
  4. Verify the Generated Code:

    go
    // generated_code.go // Code generated by gen.go; DO NOT EDIT. package main func GeneratedFunction() { fmt.Println("This is a generated function.") }
    • The generated_code.go file should be created with the content specified in the code generation script.
  5. Use the Generated Code:

    go
    // main.go package main //go:generate go run tools/gen.go import "fmt" func main() { fmt.Println("Hello, Go Generate!") GeneratedFunction() }
    • Update main.go to call the generated function.
  6. Run the Program:

    sh
    go run .
    • This should output:
      sh
      Hello, Go Generate! This is a generated function.

Summary

Using go generate can significantly enhance productivity by automating repetitive tasks and ensuring that generated code is consistent and up-to-date.

Becoming a Senior Go Developer: Mastering Go and Its Ecosystem