DEV Community

Cover image for go:generate 101
Francesco Di Donato
Francesco Di Donato

Posted on

go:generate 101

How to use go:generate?

support code

Setup

terminal

go mod init github.com/<username>/<reponame>
Enter fullscreen mode Exit fullscreen mode

Create two files. main.go will use gen.go as generator.

terminal

touch main.go gen.go
Enter fullscreen mode Exit fullscreen mode

main.go simply logs "World!" and runs the generator via the special comment.

main.go

package main

//go:generate go run gen.go

import "fmt"

func init() {
    fmt.Println("main.go#main.init")
}

func main() {
    fmt.Println("World!")
}

Enter fullscreen mode Exit fullscreen mode

NOTE: There is no space between the slashes and go:generate.

NOTE: not only gen.go, but go run gen.go.

gen.go declares package main, which would be forbidden were it not for the special comment.

gen.go

//go:build ignore

package main

import "fmt"

func init() {
    fmt.Println("gen.go#main.init")
}

func main() {
    fmt.Println("Hello")
}

Enter fullscreen mode Exit fullscreen mode

NOTE: There is not space between the slashes and go:build.

Usage

terminal

go generate ./...
Enter fullscreen mode Exit fullscreen mode

Output

gen.go#main.init
Hello
Enter fullscreen mode Exit fullscreen mode

terminal

go run .
Enter fullscreen mode Exit fullscreen mode

terminal

main.go#main.init
World!
Enter fullscreen mode Exit fullscreen mode

Although the subcommand name is generate, the **generator* need not generate a file.*

References

Oldest comments (0)