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:
Add //go:generate
Directives in Source Files:
//go:generate
comments in your Go source files to specify the commands that should be run when go generate
is executed.Run go generate ./...
:
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!")
}
//go:generate
directive specifies that the echo
command and a Go script (tools/gen.go
) should be run.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")
}
generated_code.go
with a function GeneratedFunction
.Run go generate
:
shgo generate ./...
//go:generate
directives in the current package and its subdirectories and executes the specified commands.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.") }
generated_code.go
file should be created with the content specified in the code generation script.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()
}
main.go
to call the generated function.Run the Program:
shgo run .
shHello, Go Generate! This is a generated function.
//go:generate
comments to specify commands for code generation.go generate ./...
to execute all specified generation commands within the package and its subdirectories.Using go generate
can significantly enhance productivity by automating repetitive tasks and ensuring that generated code is consistent and up-to-date.