Lesson 56 of 60 · Go
Generating Go Code – `go generate` & Templates
Duration: 20 minutes
Code Generation
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
go generate runs commands specified in source files.
//go:generate stringer -type=Day
type Day int
const (
Sunday Day = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
Run with:
$ go generate ./...
Using text/template to emit code
import "text/template"
const tmpl = `package {{.Pkg}}
// {{.Name}} holds {{.Desc}}
type {{.Name}} struct { {{range .Fields}}{{.Name}} {{.Type}} ` + "`json:\"{{.JSON}}\"`" + `{{end}} }
`
type field struct { Name, Type, JSON string }
data := struct{ Pkg, Name, Desc string; Fields []field }{ "model", "User", "user data", []field{{"ID","int","id"},{"Name","string","name"}} }
t, _ := template.New("code").Parse(tmpl)
t.Execute(os.Stdout, data)